Search code examples
c#linqinheritanceef-code-firsttable-per-type

Query on two inherited classes in EF Code First


I'm using EF code first and I have two classes that inherited from a base class(TPT):

public class Party
{
   public int PartyId {get; set;}
}
public Person:Party
{
   string FirstName { get; set; }  
   string LastName { get; set; }  
} 
public Organization:Party
{
   string Name { get; set; }  
} 

Now, I want to create a query to fetch all Persons that their LastNames are equal to "SomeName" and all Organizations that their Name begins with "A" in one transaction. Something like this

IList<Party> GetParties(string name, string organizationName)
{
   IList<Party> result = new List<Party>();   
   using(var context = new MyContext())
   { 
      var persons = context.Parties.OfType<Person>().Where(t=>t.LastName = name) ;
      var organizations = context.Parties.OfType<Organization>().Where(t=>t.Name.StartWith(organizationName));
      //return merge of persons and organizations 
   }
}

Is there any way to do this?


Solution

  • You can do

    context.Parties.OfType<Person>().Where(t=>t.LastName = name).OfType<Party>()
    .Concat(context.Parties.OfType<Organization>()
                   .Where(t=>t.Name.StartWith(organizationName)))
    

    You don't have to cast the second collection to Party because it is concatenated with an IQueryable<Party> which is covariant with IQueryable<Organization>.