LINQ to SQL Inheritance problem


Can anyone solve this issue?

Imagine you have two classes, ProjectManager and Developer. Both are of type Person (except for really spineless PMs and uber-nerd developers), and every ProjectManager has a number of Developers under their command.

LinqSql1

You correctly set the discriminator value and make Person an abstract class:

LinqSql2

You then want to create a one-to-many relationship between PM and Developer so that in code you can navigate between e.g. a ProjectManager and their Developers using something like:

foreach (var Pm in Context.ProjectManagers)
    System.Console.WriteLine ("Project Manager Id {0} has {1} many developers", Pm.PersonId, Pm.Developers.Count());

Also bear in mind that both classes (well, all three in fact) share the same physical database table in LINQ-to-SQL’s single-table-inheritance model. So then you try to add an Association between ProjectManager and Developer, by joining between Developer.ProjectManagerPersonId and ProjectManager.PersonId: –

LinqSql3

Whoops! Where’s the PersonId column on the ProjectManager? This should be displayed in the drop-down because it’s inherited from the Person base class. But it’s not there, so you can’t add the Association between the Developer and ProjectManager.

The workaround I found was to use the designer to add an Association between Person and Developer instead. The most obvious problem here is that all classes which derive from Person has a collection of Developers underneath them – even a Developer itself! This is obviously not what you want. So, I tried going into the designer.cs of the DataContext, and changing all the Association objects etc. to point to the Project Manager instead of Person. And believe it or not, it seems to work! This is not ideal though – even if you were to move the code out of the designer.cs into your partial class, it’s still a hack.

So, is this a bug with Linq To Sql or just me trying something out that is going “too far”. And please don’t mention ADO .NET Entity Framework as we’re using L2S on the project that I’ve got this issue on.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s