【问题标题】:Query base entity to retrieve all derived entity's data using Linq to Entities使用 Linq to Entities 查询基础实体以检索所有派生实体的数据
【发布时间】:2014-10-28 09:44:32
【问题描述】:

我的模型中有以下类:

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 Fluent API 查询 Parties 并返回如下 PartyViewModel 的结果?

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

【问题讨论】:

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


    【解决方案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();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-07
      • 2011-07-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多