linq将2个表组合成一个列表

时间:2014-02-15 03:33:48

标签: c# sql .net linq

我在db中有2个表 - 一个是EmploymentRecords,一个是EmploymentVerificationRecords

我想查询两个表并返回一个List

我有一个模型(简化示例):

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(),因为这些结果IsVerification将为True

1 个答案:

答案 0 :(得分:2)

您现在可以选择DB中的所有内容(但我宁愿使用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));