im using vs2010 and have a sql statment shown below
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
i need the above converted to a linq statement, lambda would be nice
all tables are in the dbml
this is the mess i have so far, obviously it wont work
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));
any help would be apprieciated and thanks in advance
ok thanks guys for your help, i ended up with somethign like this
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);
}
note the constructors , SlDepartment(lkDept dept) and SlDepartments(IEnumerable collection) is this an appropriate way of working with LINQ?
any gotachas i might be missing, ie potentials for exceptions or perforamnce issues with the above or the whole solutions?
Your attempt seems correct but just should change contains -> Any and also is incomplete: