简体   繁体   English

条件linq查询

[英]Conditional linq query

What would be the best approach for converting this SQL to linq? 将此SQL转换为linq的最佳方法是什么?

I've earlier made views in the database based on such an sql, and then query the view with linq. 我之前已经基于这样的sql在数据库中创建了视图,然后使用linq查询该视图。 But I've would like to know if there are other approaches. 但是我想知道是否还有其他方法。

The SQL finds the assigned object for an task. SQL查找任务的分配对象。 The task table contains three foreign key columns, as the assigned to may be from Department, Position or a Person. 任务表包含三个外键列,分配给这些外键的列可能来自Department,Position或Person。 Only one is allowed. 只允许一个。

SQL: 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

Using LinqToEF 使用LinqToEF

You can write it like this: 您可以这样写:

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
        };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM