有条件的linq查询

时间:2014-09-09 18:45:07

标签: c# sql linq

将此SQL转换为linq的最佳方法是什么?

我之前基于这样的sql在数据库中创建了视图,然后使用linq查询视图。但我想知道是否有其他方法。

SQL查找任务的已分配对象。任务表包含三个外键列,因为分配的可能来自Department,Position或Person。只允许一个。

SQL:

SELECT   id,
         title,
         assigned_to = (case
            when idAssignedDepartment is not null then (select description from department where id = idAssignedDepartment)
            when idAssignedPosition is not null then (select description from position where id = idAssignedPosition )
            when idAssignedPerson is not null then (select fullname from person where id = idAssignedPerson )               
            end)
FROM     task

使用LinqToEF

1 个答案:

答案 0 :(得分:2)

你可以这样写:

var q = from t in task
        from dep in department.Where(x => x.id == t.idAssignedDepartment).DefaultIfEmpty()
        from pos in position.Where(x => x.id == t.idAssignedPosition).DefaultIfEmpty()
        from per in person .Where(x => x.id == t.idAssignedPerson).DefaultIfEmpty()
        select new
        {
            t.id,
            t.title,
            assigned_to = t.idAssignedDepartment != null ? dep.description :
                          t.idAssignedPosition != null ? pos.description :
                          t.idAssignedPerson != null ? per.fullname : 
                          null
        };