2014-02-15 56 views
3

我在DB 2個表 - 一個是EmploymentRecords一個是EmploymentVerificationRecordsLINQ結合2個表到一個列表

我要查詢兩個表,並返回一個列表

我有一個模型(簡化的例子):

Public Class Record 
{ 
    int ID {get; set;} 
    string name {get; set;} 
    bool IsVerification {get; set;} 
} 

我希望有一些類型的查詢,在LINQ,如:

var records = from a in _context.EmploymentRecords 
     join b in _context.EmploymentVerificationRecords on a.id equals b.id 
     where a.UserID = 1 
     select new Record() { .ID = a.id, .name = a.name, .IsVerification = false} 
     // I also want to select a new Record() for each b found 

看 - 我也希望有一個新的Record()加入結果在第二個表中的每個記錄,這些結果IsVerificationTrue

回答

2

,因爲它現在選擇您可以從數據庫中選擇一切(但我寧願使用join/into做到這一點),然後使用LINQ to Objects將結果展平成一個大集合。

之後應該做的伎倆:

var records 
    = (from a in _context.EmploymentRecords 
     join b in _context.EmploymentVerificationRecords on a.id equals b.id into bc 
     where a.UserID = 1 
     select new { 
      a = new Record() { ID = a.id, name = a.name, IsVerification = false}, 
      b = bc.Select(x => new Record() { ID = x.ID, name = b.name, IsVerification = true }) 
     }).AsEnumerable() 
     .SelectMany(x => (new [] { x.a }).Concat(x.b));