0

我已經按照我的模型類:查詢基礎機構檢索使用LINQ所有派生​​實體的數據實體

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

我如何可以查詢在Parties並返回結果如下PartyViewModel,使用LINQ到實體Fluent API

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

e.g如果我有以下記錄:

 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

使用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();