AFetter
AFetter

Reputation: 3614

Count distinct values in many-to-many relationship

I have one relation many-to-many on my EF.

Select * from [Group]
Select * from [User]
select * from [RelUserGroup] //relation between ground and users

I like know how many districts users I have on table RelUserGroup. This is very simple on SQL but in EF I doesn't have this table.

How I count how many users I have in all groups !

Group
GroupId     Name              
----------- ------------------
1           DCE Administrators
2           Dispatcher        
3           Team Managers     
4           Resolver          
5           Requestor 

User
UserId      UserName
----------- ---------
1           anderson
2           Fabio

RelUserGrou
GroupId     UserId
----------- -----------
1           1
2           1
4           1

In this case my count is 1, because userId = 2 isn't in any group.

Upvotes: 2

Views: 505

Answers (1)

p.s.w.g
p.s.w.g

Reputation: 149078

Perhaps something like this:

var result = db.Users.Count(u => u.Groups.Any());

Or alternatively

var result = db.Groups.SelectMany(g => g.Users).Distinct().Count();

Upvotes: 2

Related Questions