使用Linq或Entity Framework查询加入比较列和变量值

时间:2021-02-02 09:37:18

I want to apply join into command using a column and a variable value.

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

here's the code (the partial part of the query where I have an issue):

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

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

This code works, but I also need to filter the db.user_tests by the user_id. I have that user_id in a variable userId inside the function.

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

So I decided to write the query as follows:

所以我决定编写如下查询:

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()

But I get "Operator && cannot be applied to operands of type long and bool" error.

但我得到“运算符&&不能应用于long类型和bool类型的操作数”错误。

I tried with equal but it throws several errors.

我尝试平等,但它抛出了几个错误。

I also tried with the two column join, but I use a variable in the comparison so it doesn't work.

我也试过两列连接,但我在比较中使用了一个变量,所以它不起作用。

How can I use the join into with a column comparison and a variable at the same time?

如何将连接同时用于列比较和变量?

1 个解决方案

#1


1  

If you want to join on several properties you should use anonymous objects for that:

如果要加入多个属性,则应使用匿名对象:

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()

Also make sure that anonymous objects have properties with same types and names.

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

But thus userId is not part of your a object it makes no sense to use that variable as part of join. You can simply join on test_id and use filter by user_id:

但是因此userId不是您对象的一部分,将该变量用作连接的一部分是没有意义的。您可以简单地加入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()

#1


1  

If you want to join on several properties you should use anonymous objects for that:

如果要加入多个属性,则应使用匿名对象:

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()

Also make sure that anonymous objects have properties with same types and names.

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

But thus userId is not part of your a object it makes no sense to use that variable as part of join. You can simply join on test_id and use filter by user_id:

但是因此userId不是您对象的一部分,将该变量用作连接的一部分是没有意义的。您可以简单地加入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()