简体   繁体   中英

Linq to entities - How to define left join for grouping?

We have two tables - Tasks and TasksUsers (users assigned to task). Task has EntityCollection called TaskUsers.

This query returns number of tasks per username:

model.TaskCountByAssignee =
            (
            from t in TaskRepository.List()
            from tu in t.TaskUsers
            group tu by tu into tug
                select new {Count = tug.Count(), UserName = tug.Key.Username}).ToList()

This query returns:

Administrator 11
LukLed 5

I want it to return:

Administrator 11
LukLed 5
null 10

Some of tasks don't have any assignment, but I still want them in my result set. Normally, in SQL, it is achieved by changing join to left join . In Linq, outside EF, I could use DefaultIfEmpty(). How can it be done in linq to entities?

My first try would be:

model.TaskCountByAssignee = (
        (from t in TaskRepository.List()
         from tu in t.TaskUsers
         group tu by tu.UserName into tug
         select new {Count = tug.Count(), UserName = tug.Key})
        .Union(from t in TaskRepository.List()
               where !t.TaskUsers.Any()
               group t by 1 into tug
               select new {Count = tug.Count(), UserName = null}).ToList();

Or something along those lines. Or just use two queries. I don't know if this is the best way, though. As I noted in comments, this is far easier in EF 4.

I would suggest looking here which goes through left outer joins with EF:

http://geekswithblogs.net/SudheersBlog/archive/2009/06/11/132758.aspx

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