Is there a good reason not to rely on the integrity of the database key in business logic?

I am writing a method that will allow you to embed a link table in my database, and I wonder if I need to check first to make sure that the specified PKs really exist in the linked tables. It seems logical to me that I can simply rely on the database 100% to ensure these FK restrictions for me, as well as to prevent duplicate entries in the table through the PK table. Actually, it seems like a pretty redundant and waste of resources for me to check them in advance if the DB will check them anyway. Also, note that I'm talking about the basic principles of RDBMS here; I expected that they would be equally respected even when switching to another data storage engine.

So, in these circumstances, is there any good reason not to rely on the database completely to ensure data integrity for FK and PK? In other words:

using (var context = new MyDbContext()) { try { context.LinkEntries.Add(new LinkEntry { key1 = x, key2 = y }); return context.SaveChanges() > 0; } catch (DbUpdateException) { // Duplicate, or foreign key violation return false; } } 
+4
source share
1 answer

Relational databases will provide referential integrity - if you configured foreign keys correctly.

1) This ensures that key1 and key2 actually point to rows in the primary tables.

2) If you also want the link table to have only one row with a specific pair of foreign keys, you will need to add a unique constraint to the database of these columns.

If you use a foreign key pair as the primary key of the link table, you should be fine.

+2
source

All Articles