Question

I'm writing a method that will allow inserts into a link table in my DB, and I'm wondering whether I need to first check to make sure the PKs specified actually exist in the linked tables. It seems logical to me that I can just rely 100% on the database to enforce these FK constraints for me, as well as preventing duplicate table entries via the table's PK. In fact, it seems quite redundant and a waste of resources for me to check these beforehand if the DB is just going to check them anyway. Also, note that I'm talking about very basic RDBMS concepts here; I'd expect them to be equally enforced even if switching to another data store mechanism.

So under these circumstances, is there any good reason not to rely on the database entirely to ensure data integrity for the 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;
    }
}
Was it helpful?

Solution

Relational databases will enforce referential integrity - assuming you've set up the foreign keys correctly.

1) This will ensure key1 and key2 actually point to rows in the primary tables.

2) If you also want to ensure only one row with a particular pair of foreign keys can exist in the link table, you will have to add a unique constraint in the database on those columns.

If you are using the pair of foreign keys as your link table primary key, you should be fine.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top