简体   繁体   English

C# LINQ INNER JOIN 返回错误计数

[英]C# LINQ INNER JOIN is returning wrong count

I have the following sql with JOIN but which returns a record count for 50 but when I convert it to LINQ, I am not getting the matching count.我有以下带有 JOIN 的 sql 但它返回的记录计数为 50 但是当我将其转换为 LINQ 时,我没有得到匹配的计数。 I noticed that when I add the ON clause, the visual studio intellisense dropdown does not show the ID property for the 2nd table.我注意到,当我添加 ON 子句时,visual studio intellisense 下拉列表不显示第二个表的 ID 属性。 I am wondering if that is an issue.我想知道这是否是一个问题。

Here is the simple SQL这里是简单的 SQL

SELECT * FROM Table1 T1 JOIN Table2 T2 ON T1.MyId = T2.MyId WHERE T1.IsCompleted

Here is my lamba LINQ with the comment where the VC Intellisense is not working right.这是我的 Lamba LINQ 评论,其中 VC Intellisense 无法正常工作。 For table2, the intellisense dropdown, it is only showing Equals, GetHashCode, GetType, and ToString.对于 table2,intellisense 下拉列表,它只显示 Equals、GetHashCode、GetType 和 ToString。 Just manually type the MyId and everything successfully builds but the count is too high.只需手动输入 MyId 即可成功构建所有内容,但计数太高。 Thanks谢谢

var test = this.myDbContent.Table1
           .Join (this.myDbContent.Table2
             table1 => table1.MyId,
             table2 => table2.MyId, 
             (table1, table2) => new { table1, table2}
           )
           .Where (joinedTable => joinedTable.Table1.IsCompleted == 1)

Join is the simple LINQ operation, but better understandable via LINQ Query. Join 是简单的 LINQ 操作,但通过 LINQ 查询可以更好地理解。

var query = 
    from t1 in myDbContent.Table1
    join t2 in myDbContent.table2 on t1.MyId equals t2.MyId
    where t1.IsCompleted
    select new 
    {
        t1,
        t2
    };

If you still have different results, probably MyId is nullable field and EF also matches nulls.如果您仍然有不同的结果,可能MyId是可为空的字段,而 EF 也匹配空值。

It can be disabled via options configuration:可以通过选项配置禁用它:

builder.UseSqlServer(ceConnection, x => x.UseRelationalNulls(true));

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

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