Pergunta

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?

Foi útil?

Solução

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

Outras dicas

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;
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top