左边使用Linq加入条件

时间:2012-10-10 18:55:40

标签: c# sql linq lambda

我正在尝试使用C#代码中的条件创建左连接。我可以在SQL Server中编写它,但我在编写lambda表达式时遇到问题。这是我的SQL代码的一个粗略部分:

Select x.RequestId, aud.DepartmentId
From Requests x
Left Join UserDepartment ud on x.AssignedToTeam = ud.DepartmentId and ud.User = 'Joe'

我知道如何编写左连接,但我不熟悉如何或是否可以添加条件。

3 个答案:

答案 0 :(得分:3)

怀疑你想要这样的东西:

var query = from request in db.Requests
            join department in db.UserDepartments
                                 .Where(dep => dep.User == "Joe")
              on request.AssignedToTeam equals department.DepartmentId
              into departments
            from dep in departments.DefaultIfEmpty()
            select new { request.RequestId,
                         DepartmentId = dep == null ? null : (int?) dep.DepartmentId
            };

(如果有必要,显然会改变你想要处理缺少部门ID的方式。)

答案 1 :(得分:0)

答案 2 :(得分:0)

var request = db.View.Join(
    db.UserDepartment.Where(w=>w.User=="Joe"),
    a=>a.AssignedToTeam, 
    b=>b.DepartmentId, 
    (a,b)=> new {View = a, UserDepartment = b});