查询基本实体以使用Linq to Entities检索所有派生实体的数据

时间:2014-10-28 09:44:32

标签: c# entity-framework inheritance linq-to-entities fluent-interface

我的模型中有以下课程:

public class Party
{
     public int Id {get; set;}
}

[Table("Person")]
public class Person:Party
{
     public string FirstName {get; set;}
     public string LastName {get; set;}
}

[Table("Organization")]
public class Organization:Party
{
     public string Name {get; set;}
}

如何使用linq-to-entities Parties查询PartyViewModel并将结果返回到Fluent API以下?

public PartyViewModel
{
    public int Id {get;set;}  
    public string FirstName {get;set;}  
    public string LastName {get;set;}  
    public string Name {get;set;}  
}

例如,如果我有以下记录:

     Person Table
------------------------   
Id   FirstName  LastName
 0     John      Smith  


   Organization Table
------------------------   
Id          Name  
 1        Microsoft

我想,查询返回:

         PartyViewModel  
---------------------------------
Id   FirstName  LastName    Name
 0     John      Smith      null
 1     null      null     Microsoft

1 个答案:

答案 0 :(得分:1)

使用SQL UNION可以满足您的需求。

var q1 = from p in db.Persons
         select new PartyViewModel {
           Id = p.Id,
           FirstName = p.FirstName,
           LastName = p.LastName,
           Name = null
         };
var q2 = from o in db.Organizations
         select new PartyViewModel {
           Id = o.Id,
           FirstName = null,
           LastName = null,
           Name = o.Name
         };

var vm = q1.Union(q2).ToList();