【问题标题】:Join into with column and variable value compared using Linq or Entity Framework queries使用 Linq 或实体框架查询与列和变量值进行比较
【发布时间】:2016-02-17 17:22:13
【问题描述】:

我想使用列和变量值应用join into 命令。

这是代码(我有问题的部分查询):

 join p in db.user_tests on a.id equals p.test_id into g3
 from x3 in g3.DefaultIfEmpty()

此代码有效,但我还需要通过 user_id 过滤 db.user_tests。我在函数内部的变量 userId 中有那个 user_id。

所以我决定将查询写成如下:

join p in db.user_tests on a.id equals p.test_id && userId equals p.user_id into g3
from x3 in g3.DefaultIfEmpty()

但我收到"Operator && cannot be applied to operands of type long and bool" 错误。

我尝试使用equal,但它引发了几个错误。

我也试过the two column join,但我在比较中使用了一个变量,所以它不起作用。

如何同时使用 join into 进行列比较和变量?

【问题讨论】:

    标签: sql entity-framework linq entity-framework-6


    【解决方案1】:

    如果你想加入几个属性,你应该使用匿名对象:

    join p in db.user_tests 
    on new { a.id, userId } equals new { id = p.test_id, userId = p.user_id } into g3
    from x3 in g3.DefaultIfEmpty()
    

    还要确保匿名对象具有相同类型和名称的属性。

    但因此userId 不是您的a 对象的一部分,使用该变量作为连接的一部分是没有意义的。您可以简单地加入test_id 并使用user_id 过滤器:

    join p in db.user_tests.Where(x => x.user_id == userId) 
    on a.id equals np.test_id into g3
    from x3 in g3.DefaultIfEmpty()
    

    【讨论】:

    • 是的,我正在检查相同的类型,因为它之前通过错误。所以我再次进行投射和检查。
    • @IdanShechter 如果匿名对象的顺序、名称和类型相同,则查询将被编译并执行,没有任何问题。生成的查询看起来像ON a.Id = p.test_id AND @userId = p.user_id,用户 ID 将作为查询参数传递
    猜你喜欢
    • 1970-01-01
    • 2020-08-31
    • 1970-01-01
    • 1970-01-01
    • 2021-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-25
    相关资源
    最近更新 更多