2013-10-29 82 views
0

我第一次使用EF代碼,我有一個從基類繼承兩個類(TPT):查詢兩個繼承的類在EF代碼第一次

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; } 
} 

現在,我想創建一個查詢獲取所有Person s的LastName s等於「SomeName」,並且所有Organization s的Name在一次交易中以「A」開頭。 像這樣

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

有沒有辦法做到這一點?

回答

1

你可以做

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

您不必到第二集中轉換爲Party,因爲它與IQueryable<Party>這是協變與IQueryable<Organization>串聯。

-1

我做了一些LINQPad擺弄,我相信這是你想要的結果。

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; 
}