I’m coding an app that uses an existing database, that database has some tables I cannot modify at all, I can nevertheless add new tables.
So, let’s say I have an old table, Cities, to which I can read, create, update and delete but I cannot modify the schema.
I then add a new table, Clients, which has a foreign key to Cities, but I cannot add a relation on the database server (SQL SERVER 2008) as it also modifies the Cities table, adding a relation.
So I thought maybe if I add them both to my linq-to-sql context, and add the relation there, linq-to-sql would be clever enough to check for referential integrity for me, even though the relation is not established on the database, it’s on the context.
I created a new project to try that out, I added two simple tables without a relation, then added the relation on the linq-to-sql designer, and tried to force an exception on referential integrity, but looks like it’s not working.
DBContextDataContext db = new DBContextDataContext();
City l = new City();
l.name= "Buenos Aires";
db.Cities.InsertOnSubmit(l);
Client c = new Client();
c.name = "Mike";
c.City = l;
db.Clients.InsertOnSubmit(c);
db.SubmitChanges(); // This works
db.Cities.DeleteOnSubmit(l);
db.SubmitChanges(); // This shouldn't work, but it works
Any idea if it’s possible to force the referential integrity? Or adding the relation on the DB is the only way?
You can override the SubmitChanges method on the DataContex, and verify the changes made.
But feels painful. Are you absolutely sure, that you can’t talk to the DBA to make the required changes? You can (i guess you are allowed to too) add a table, but can’t add a foreign key, so the database may contain invalid data?
Also, if you have to verify changes this way, that means you have to make more queries to the db to verify all keys, etc is valid.
Or this IS definitely a hack:
And very fragile: if anything changes in the original db, you have to change it in your “dummy” db…
So still, try to reason with your boss, the DBA, or who made this decision, because you can’t prevent a delete by someone else in the referenced table.