简体   繁体   中英

Conditional linq query

What would be the best approach for converting this SQL to linq?

I've earlier made views in the database based on such an sql, and then query the view with linq. But I've would like to know if there are other approaches.

The SQL finds the assigned object for an task. The task table contains three foreign key columns, as the assigned to may be from Department, Position or a Person. Only one is allowed.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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