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; } }
source share