views:

65

answers:

1

The problem I'm having is while using Linq2Sql with inheritance after declaring a new instance of the inherited class the discriminator property is still set to its initial value, not the correct value for the sub-type. It gets the correct value after attaching it to a context and calling SubmitChanges(). There are times where I want to declare a new object of the inherited type and call methods on the base class with the base class knowing inherited type it is working with and the most logical choice would be to use the discriminator property.

Is there a way to force the setting of the discriminator property? I don't want to go to all my sub-classes and implement the OnCreated() partial method for something the context already knows how to do.

A: 

I did come up with a slightly better workaround than putting code in the OnCreated() method of each inheriting class and figured I'd leave it here in case anyone stumbles here.

In the OnCreated() of the base class I added code that looked similar to this:

partial void OnCreated()
{
    if (this is BaseClass1)
    {
        this.[DiscriminatorProperty] = DiscriminatorValueForBaseClass1;
    }
    else if(this is BaseClass2)
    {
        this.[DiscriminatorProperty] = DiscriminatorValueForBaseClass2;
    }
}

It is still duplicating the functionality that the context already knows how to do but at least I'm not implementing the OnCreated() in every base class. I also don't like the fact that if a new class is added or a discriminator value changes you have to update it in the DBML and in the OnCreated(). For this reason I'd still like a way for the context to assign the value, in fact it should be doing this when the inherited class is created.

Matt