简体   繁体   English

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

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

I need to write a linq based on the following query.我需要根据以下查询编写一个 linq。

IN SQL Server,在 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)

This gives me 300 records这给了我 300 条记录

In LINQ,在 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;
            }
        }

I am getting 5000 records here.我在这里得到 5000 条记录。

I have missed left outer join and C.EXID = (some number/NULL) condition.我错过了左外连接C.EXID = (some number/NULL)条件。 How to do that in the query?如何在查询中做到这一点?

I should only get the 300 records.我应该只得到 300 条记录。

This query will create LEFT JOIN:此查询将创建 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
    };

This should do it这应该这样做

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
    };

The complexity lies in the fact that we have to place the join into table3Joined and then we can do from C in table3Joined.DefaultIfEmpty()复杂性在于我们必须将连接放入table3Joined然后我们可以from C in table3Joined.DefaultIfEmpty()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM