Sql – Table relationships in LINQ to SQL

foreign-keyslinq-to-sql

Assume I have a two tables, A and B. Table A has a primary key called A_ID of type int, and table B has a foreign key called A_ID.

When I add the two tables to a LINQ to SQL data context class it correctly creates the classes and the association between them.

My question is, class B will have a property of type int called A_ID. It will also have property called A, of type A.

Now, if at runtime, I make a LINQ to SQL call which populates an instance of B, B.A_ID and B.A.A_ID will be the same value. What is stopping a developer from making some mistake and putting a different value in B.A_ID than is in B.A.A_ID?

In a database you couldn't do this because of the foreign key constraints, but how do the LINQ to SQL classes enforce those constraints on the client side?

Best Answer

LINQ to SQL, when attached to a relational database, is really just building SQL for you and so if you do something illegal in the database (like violate a foreign key constraint) it's the database that is really stopping you, not LINQ itself. And constraints in LINQ to SQL itself are just retreived from the database.

So, unless you're talking about attaching it to an XML segment or the like (and I don't see that your question suggests that) then LINQ really isn't enforcing anything in and of itself. It's really just a very sophisticated codewriter.

Edit: I said that LINQ to SQL is just a codewriter, but I should note that the metadata that lets you use the strong typing, etc. is nice. I don't mean to belittle the product.