即时通讯使用vs2010并有一个sql语句如下所示
select deptId, deptName, Detail from lkDept where deptId in (select deptId from lkDeptLinks where userRef in (select ref from lkUsers where userId = @userId)) order by deptName
我需要将上面转换为linq语句,lambda会很好
所有表都在dbml
中这是我到目前为止的混乱,显然它不会起作用
var queryUsers = dc.lkUsers.Where(p => p.UserID == userId);
var queryLinks = dc.lkDeptLinks.Where(p => queryUsers.ref.contains(p.ref));
var queryDept = dc.lkDepts.Where(p => queryLinks.deptid.contains(p.deptid));
任何帮助都会得到应用并提前致谢
using (var dc = new myDataContext(DB.GetConnectionString()))
{
var queryUsers = dc.lkUsers.Where(p => p.UserID == userId).Select(p => p.@ref);
var queryLinks = dc.lkDeptLinks.Where(p => queryUsers.Any(x => p.UserRef == x )).Select(p => p.DeptId);
var queryDept = dc.lkDepts.Where(p => queryLinks.Any(x => p.DeptID == x)).OrderBy(p => p.deptName).Select(p => new SLDepartment(p));
if (queryDept.Any())
return new SLDepartments(queryDept);
}
请注意构造函数,SlDepartment(lkDept dept)和SlDepartments(IEnumerable集合)是否适合使用LINQ?
任何遗漏我可能会失踪,即上述或整个解决方案的异常或性能问题的可能性?
答案 0 :(得分:1)
您的尝试似乎是正确的但只是应该更改包含 - >任何也是不完整的:
var queryUsers = dc.lkUsers.Where(p => p.UserID == userId);
var queryLinks = dc.lkDeptLinks.Where(p => queryUsers.ref.Any(x=>x== p));
var queryDept = dc.lkDepts.Where(p => queryLinks.deptid.Any(x=> x == p.deptid));
return queryDept
.Select(x=>new {ID = x.deptId, Name = x.deptName, Detail = x.Detail})
.ToList();