如何使用基于 SQL 查询的联接在 C# 中编写 LINQ?

How to write LINQ in C# with joins based on SQL Query?

我需要根据以下查询编写一个 linq。

IN SQL 服务器,

select EXID,ID,NAME 
from Table1 A
join Table2 B on A.BXID = B.BID
left outer join Table3 C ON C.AXID = A.ID
AND C.EXID = (some number/NULL)

这给了我 300 条记录

在 LINQ 中,

try
        {
            using (var context = new cltransformationContext())
            {
                var Details = (
                            from A in context.Table1
                            join B in context.Table2 on A.BXID equals B.BID
                            join C in context.Table3 on A.ID equals C.AXID  
                select new Table1()
                           {
                            ID = A.ID,
                            name = A.NAME + '-' B.Name
                            }).ToList();
                return Details;
            }
        }

我在这里得到 5000 条记录。

我错过了 left outer joinC.EXID = (some number/NULL) 条件。 如何在查询中做到这一点?

我应该只得到 300 条记录。

此查询将创建 LEFT JOIN:

var query =
    from A in context.Table1
    join B in context.Table2 on A.BXID equals B.BID
    from C in context.Table3.Where(C => A.ID == C.AXID && C.EXID == ...).DefaultIfEmpty()
    select new Table1
    {
        ID = A.ID,
        name = A.NAME + '-' B.Name
    };

应该这样做

var query =
    from A in context.Table1
    join B in context.Table2 on A.BXID equals B.BID
    join table3 in context.Table3.Where(X => x.EXID = 123) on A.ID == table3.AXID into table3Joined
    from C in table3Joined.DefaultIfEmpty() // this is how we do the left join
    select new Table1
    {
        ID = A.ID,
        name = A.NAME + '-' B.Name
    };

复杂之处在于我们必须将连接放入 table3Joined 然后我们可以做 from C in table3Joined.DefaultIfEmpty()