[英]How do I create multiple joins using LINQ extension methods?
I'm having trouble using LINQ method calls with multiple joins. 我在使用带有多个联接的LINQ方法调用时遇到麻烦。 I'm trying to do something like this: 我正在尝试做这样的事情:
if (!isDepSelect)
{
query = (from Items in db.DEPARTMENTs
select Items);
}
else
{
query = (from Items in db.DEPARTMENTs
from gDept in db.DEPT_PROFILE
from wAccess in db.WEB_ACCESS
where Items.DEPT_CODE == gDept.DEPT_CODE && gDept.USER_ID == wAccess.USER_ID && wAccess.EMP_ID == id
select Items);
}
I had done this: 我这样做了:
IQueryable<DEPARTMENT> query = db.DEPARTMENTs;
if (isDepSelect)
{
query = query.Join(db.DEPT_PROFILE,depts => depts.DEPT_CODE,prof => prof.DEPT_CODE,(depts, prof) => depts);
}
But now I don't know how to add the JOIN of DEPT_PROFILE table with the WEB_ACCESS table and the condition of the EMP_ID = id. 但是现在我不知道如何将DEPT_PROFILE表的JOIN与WEB_ACCESS表以及EMP_ID = id的条件相加。
The reason I'm doing this is that the isDepSelect boolean is not the only condition that this query will change its relations and I need someway to add this relations without repeating my LINQ for each of my conditions. 我这样做的原因是isDepSelect布尔值不是此查询将更改其关系的唯一条件,并且我需要以某种方式添加此关系,而不必为每个条件都重复LINQ。
Thank you for your time. 感谢您的时间。
Try with, 试试看,
List<DEPARTMENTs> list = db.DEPARTMENTs.Join(db.DEPT_PROFILE, dept => dept.DEPT_CODE, prof => prof.DEPT_CODE, (dept,prof) => new {dept, prof})
.Join(Wdb.WEB_ACCESS, depts => depts.prof.USER_ID,web => web.USER_ID,(depts,web) => new { depts, web})
.Where(result => result.web.EMP_ID== id).Select(s => s.depts.dept).ToList<DEPARTMENTs>();
If you have your associations setup, you can do this without any joins in your code at all: 如果您有关联设置,则可以在完全不添加任何代码的情况下执行此操作:
query = db.DEPARTMENTs
.Any(item => item.DEPT_PROFILEs
.Any(gDept => gDept.WEB_ACCESSs
.Any(wAccess => wAccess.EMP_ID == id)));
Of course this is assuming a 1-m relationship between each of the objects in the graph. 当然,这是假设图中每个对象之间的关系为1-m。 You can eliminate some of the Any methods if there are 1-0..1 relationships in the graph as necessary. 如果需要,在图中有1-0..1的关系时,可以消除某些Any方法。
you should use the equals operator... 您应该使用equals运算符...
query = from Items in db.DEPARTMENTs
from gDept in db.DEPT_PROFILE
join wAccess in db.WEB_ACCESS on
gDept.DEPT_CODE equals Items.DEPT_CODE
select Items;
thats just a snippet of your example query, but you can see how i am using the join operator to introduce a 2nd table and the equals operator to declare the joining columns. 多数民众赞成在只是示例查询的摘要,但您可以看到我如何使用联接运算符引入第二个表和等于运算符来声明联接列。
This should work: 这应该工作:
query = (from Items in db.DEPARTMENTs
join gDept in db.DEPT_PROFILE
on Items.DEPT_CODE equals gDept.DEPT_CODE
join wAccess in db.WEB_ACCESS
on gDept.USER_ID equals wAccess.USER_ID
where wAccess.EMP_ID == id
select Items);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.