Code First: Query by Discriminator. I know, I'm not supposed to need to

1.6k views Asked by At

I have created TPH code-first tmodel and added the NotMappedAttribute on the required discriminator column. I can add DbSets to my context for the subclasses and query by these typed sets and code-first is still my friend.

However, say I have an entity which itself contains a collection of BaseType, some of which might be one type, and some another. How do I write a query to get the typed records? I don't want to this on a lazy-loaded, in-memory collection by the way.

Assume a class called Association and some subclasses AssocA and AssocB, which all map to the Associations table and are discriminated on AssocationTypeId. Now assume that you have an entity - call it Employee for arguments sake. So for example

class Employee
{
  public virtual Collection<Associations> MyAssociations {get;set;}
}

Now I want to query the database to find employees with AssocA = ?. I don't want just any association to be equal to ? but the particular typed association. I can't use GetType because LinqToEntities can't work with that. I can't used the AttributeTypeId because its used in the code first mapping.

What am i missing? What I am doing is reasonable. But I can't model it.

1

There are 1 answers

0
Ladislav Mrnka On

OfType operator is probably what you are looking for:

var query = from e in context.Employees
            where e.MyAssociations.OfType<AssocA>().Any()
            select e;

This will find only employees which have at least one association of type AssocA.