使用Entity Framework组合两个表

时间:2013-10-31 16:17:27

标签: c# sql entity-framework lambda entity-framework-5

我有以下查询:

{
 SELECT A.Id, C1.FullName AS APerson, C2.FullName As BPerson
 FROM TableA AS A
   LEFT JOIN TableC AS C1 ON A.FK_PersonA = C1.Id
   LEFT JOIN TableC AS C2 ON A.FK_PersonB = C2.Id
 UNION
 SELECT B.Id, B.FullName1 AS APerson, B.FullName2 AS BPerson
 FROM TableB AS B
}

我想将此转换为实体框架lambda查询,这可能吗?

数据模型

enter image description here

1 个答案:

答案 0 :(得分:2)

首先,您应该为模型创建存储库。阅读此here。 所以,你可以使用这个:

var ret = 
    (from taRec in TableA.GetAll()
    join tc1 in TableC.GetAll on taRec.FK_PersonA equals tc1.Id
      into tcRecs1
    from tcRec1 in tcRecs1.DefaultIfEmpty()
    join tc2 in TableC.GetAll on taRec.FK_PersonB equals tc2.Id
      into tcRecs2
    from tcRec2 in tcRecs2.DefaultIfEmpty()
    select new {
        taRec.Id, APerson = tcRec1.FullName, BPerson = tcRec2.FullName
    }).Union(
        from tbRec in TableB.GetAll()
        select new {
            tbRec.Id, APerson = tbRec.FullName, BPerson = tbRec.FullName
    });