Understanding Association Attribute

If you have defined foreign key constraints on your tables in the database, LINQ TO SQL would generate Association attribute on both sides of the entity meaning the parent and child entities. Let's look at the association attribute generated by Linq To SQL on both side of the entities for Customer and its Order Collection.

Customer Entity

image

Order Entity 

image

In the Customer entity we have Orders property that allow us to navigate to its related Orders.  Customer and Orders are associated in the database by foreign key relationship. Linq to SQL uses association attribute to map the foreign key relationship into parent child hierarchy.  The name attribute represents foreign key constraint name, storage specifies the private level variable that would store the collection of orders for the customer. The OtherKey argument is the most confusing to most people. OtherKey basically represents the name of the member on the related Order entity.

In the association attribute on Order entity, we are traversing from child to parent so we are setting IsForeignKey to true which basically states that we are on the child side of the relationship. Since we are on the child side of the parent child relationship we are also specifying the column in the Order entity that relates the Order to a Customer. To represent the relationship, we make use of ThisKey attribute which represents the CustomerID property on the Order entity.

1 Comment

  • Thanks - this is exactly what I was looking for. I'm trying linq attributes as a code-first experiment and was a bit confused by EntityRef's.

    I don't know if you get notifications for old posts, but are you required to have an entityRef back to the parent?

Comments have been disabled for this content.