简体   繁体   中英

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 Person s that their LastName s are equal to "SomeName" and all Organization s 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?

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> .

I did some LINQPad fiddling and I believe that this is the result you want.

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 

      result = (IList<Party>)persons.Union((IEnumerable<Party>)organizations);          
   }
   return result;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM