SQL到Linq多个表左外连接

时间:2016-03-28 14:22:30

标签: c# sql linq left-join

我在SQL中有这个查询,我希望它在LINQ using Entity Framework中实现它,但是如何在外部联接中应用多个表?

SELECT p.BookMastId as mastId
FROM BookMast p
left outer JOIN (SELECT y.BookMastId as Id, t.VrsnMastId as vrsn FROM BookReceiptMast t  
left outer JOIN BookReceiptDtl y 
on t.BookReceiptMastId = y.BookReceiptMastId) s 
on p.BookMastId = s.Id where s.vrsn = 2

1 个答案:

答案 0 :(得分:0)

您可以使用from var in collection join in语法,如下所示:

using(var cxt = new YourDataBaseContext()){
    var firstJoin = from t in cxt.BookReceiptMast
                    join y in cxt.BookReceiptDtl
                         on t.BookReceiptMastId equals y.BookReceiptMastId
                     into yTemp
                    from y in yTemp.DefaultIfEmpty()
                    select new
                    {
                        Id = y != null ? y.BookMastId : 0,
                        vrsn = t.VrsnMastId
                    };

    var allTables = from p in cxt.BookMast
                    join s in firstJoin
                         on p.BookMastId equals s.Id
                         into sTemp
                    from s in sTemp
                    where s.vrsn == 2
                    select new
                    {
                        mastId = p.BookMastId
                    };
}

我希望它可以帮到你。