[英]Get distinct results using LINQ GroupBy for complex entity relationships?
Here's a quick overview of my relationships: 以下是我的人际关系的简要概述:
one Account has many AccountRoles
one AccountRole has many UserAccountRoles
many UserAccountRoles can have one User
What I need to get is a set of all User
s for one Account
. 我需要获得的是一个Account
的所有User
的集合。
How can I do this in LINQ? 我怎么能在LINQ中这样做?
Edit: 编辑:
Here's what I've tried so far: 这是我到目前为止所尝试的:
var dto = _context.Set<Model.Account>()
.Find(account.Id);
if (dto == null)
return null;
var userAccountRoleDTOs = dto.AccountRoles
.Select(ar => ar.UserAccountRoles);
var userDTOs = userAccountRoleDTOs
.Select(uar => uar.Select(uar2 => uar2.User));
return userDTOs;
userDTOs
is a collection of collections at the return
. userDTOs
是return
集合的集合。 It doesn't make much sense to me. 这对我来说没什么意义。
Since ultimately all you want is a flattened collection for the one user, you should be able to use SelectMany()
to flatten the one-to-many relationship and then call Distinct()
at the end: 由于最终你想要的只是一个用户的扁平化集合,你应该能够使用SelectMany()
来展平一对多关系,然后在最后调用Distinct()
:
var users = dto.AccountRoles
.SelectMany(ar => ar.UserAccountRoles.Select(uar => uar.User))
.Distinct();
Or, in query form 或者,以查询形式
var users = (from ar in dto.AccountRoles
from uar in ar.UserAccountRoles
select uar.User)
.Distinct();
Or you can go the other way around: 或者你可以走另一条路:
from u in context.Users
where u.UserAccountRoles.Any(uar=>uar.AccountRole.Account.Id == someAccountId)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.