2

I've this query below working fine. However I want to implement it using Linq.

select u.ID, u.NAME
from Task t 
join BuildingUser bu ON bu.ID_BUILDING = t.ID_BUILDING 
join [User] u ON u.ID = bu.ID_USER
where t.ID IN (2,9) AND u.ID != t.ID_USER
group by u.id, u.name
having count(bu.ID_BUILDING) = (SELECT COUNT(t2.ID_BUILDING) FROM Task t2 WHERE t2.ID IN (2,9))

I don't know how to Group and use Having clause at the same time.

Gert Arnold
  • 105,341
  • 31
  • 202
  • 291
gandarez
  • 2,609
  • 4
  • 34
  • 47

1 Answers1

0

You can try something like this:

var ids = new[] { 2, 9 };
var results =
    from t in db.Tasks
    join bu in db.BuildingUsers on t.ID_BUILDING equals bu.ID_BUILDING
    group bu by bu.ID_BUILDING into bg
    join u in db.Users on bg.Key equals u.ID
    where ids.Contains(t.ID) && u.ID != t.ID_USER
    group u by new { u.ID, u.NAME } into g
    where bg.Count() == db.Tasks.Count(t2 => ids.Contains(t2.ID))
    select g.Key;

Or if you have navigation properties set up correctly, you can try this:

var ids = new[] { 2, 9 };
var results =
    from t in db.Tasks.Where(x => ids.Contains(x.ID))
    from u in t.BuildingUsers.SelectMany(bu => bu.Users)
                             .Where(x => x.ID != t.ID_USER)
    group u by new { u.ID, u.NAME } into g
    where t.BuildingUsers.Count() == db.Tasks.Count(x => ids.Contains(x.ID))
    select g.Key;
p.s.w.g
  • 146,324
  • 30
  • 291
  • 331
  • I can't do the second one because BuildingUsers is not directly related to Tasks. I was trying the first one. But the join with User seems to be wrong. If you've grouped BuildingUser by ID_BUILDING I can't join bg.key to User.ID. Am I right? What am I missing? – gandarez Aug 05 '13 at 13:03