This blog has, IMO, some great resources. Unfortunately, some of those resources are becoming less relevant. I'm still blogging, learning tech and helping others...please find me at my new home on

Monday, November 23, 2009

Sorting Out Entities with Multiple Relationships in LINQ to SQL

There is a very common scenario in data design where you define a table as having two relationships with a single (other) table.  This especially comes into play if you have anything in your model with an “assignment” where someone assigns something to someone else.

In this case, We are tracking work tickets that are created by someone for someone else.  Both are stored in the ticket table.


Above is a snip from the DBML designer for LINQ to SQL. The two arrows represent the relationships between Person and Ticket, namely, that CreatedFor and CreatedBy are Person references.  If you have set up the foreign keys in the database, these associations are created for you automatically.

Convenient, yes, but code-revealing, no.  Here’s the result of the default naming as a result of the relationship being automagically created:


Now, which is which?  Are you looking for Tickets or Tickets1?  The default method for selecting a name is pretty ambiguous.

Directing LINQ to SQL Naming

Thankfully, the designer gives us a way to control the code generation tool and its naming conventions.  Click on one of the association lines on the DBML canvas and look at your properties windows.  Verify the members that are in use in the “Participating Properties” property, then drill into the Child Property detail.

There, you can set the name of the Child property to something more meaningful to developers using your code down the road.  Or, for yourself six months from now.

image You also have a chance to disambiguate the Parent property.  And, as a result, you have more readable syntax working from the child and walking to the parent record.

No comments:

Post a Comment