[英]Linq select in list with 2 many-to-many relationships
I have the following database structure:我有以下数据库结构:
USER <--> [user_client] <--> CLIENT <--> [client_application] <--> APPLICATION用户<--> [user_client] <-->客户端<--> [client_application] <-->应用程序
USER, CLIENT and APPLICATION tables contain unique keys. USER、CLIENT 和 APPLICATION 表包含唯一键。 user_client and client_application are many-to-many tables to map USERs to CLIENTs and CLIENTs to APPs. user_client 和 client_application 是 map 用户到 CLIENT 和 CLIENT 到 APP 的多对多表。
I am using MVC5 / C#.我正在使用 MVC5 / C#。 The many-to-many tables are hidden in my Model by the Entity Framework.实体框架将多对多表隐藏在我的 Model 中。
What I want to achieve is the following: for a given USER, which has a list of CLIENTs, get the combined list of the distinct APPLICATIONs that all his CLIENTs have.我想要实现的是:对于具有客户列表的给定用户,获取他所有客户拥有的不同应用程序的组合列表。
Could you please help with the logic and the Linq query (preferably in fluent syntax if possible)?您能否帮忙解决逻辑和 Linq 查询(如果可能的话,最好使用流利的语法)? Is it possible to do it in a single query without looping through the list of clients?是否可以在不遍历客户端列表的情况下在单个查询中执行此操作?
Thank you in advance.先感谢您。
Reda雷达
不确定它是否与您的架构匹配,但是
user.clients.SelectMany(c => c.applications).Distinct()
The key is to use SelectMany instead of Select which will give you a IEnuerable<Application>
instead of a IEnumerable<IEnumerable<Application>>
关键是使用SelectMany而不是Select,它将为您提供IEnuerable<Application>
而不是IEnumerable<IEnumerable<Application>>
var user = context.Users.Where(u => u.Id == 1).Single();
var applications = user.Clients
.SelectMany(c => c.Application)
.GroupBy(a = a.Id)
.Select(a => a.First());
I want to collaborate to this question, not providing an exact solution, but additional information.我想合作解决这个问题,而不是提供确切的解决方案,而是提供更多信息。
I applied @tafia answer to my own problem, but with a slight modification to the SelectMany
method.我对自己的问题应用了@tafia答案,但对SelectMany
方法进行了轻微修改。 I replaced it with just Select
.我只用Select
替换了它。
File selectedFile = _unitOfWork.FileRepository.GetById(idFile)
selectedFile.FilePaper.Select(c => c.Paper).Distinct().ToList()
You can read about the difference between Select
and SelectMany
, here .您可以在此处阅读Select
和SelectMany
之间的区别。
I applied my modified solution on the following group of tables:我将修改后的解决方案应用于以下一组表:
Though your table seems to be different:尽管您的桌子似乎有所不同:
I'm not sure if that solution proposed by @tafia works there.我不确定@tafia 提出的解决方案是否在那里有效。
PS. PS。 If you want to make the middle tables appear in EF, a possible "fix" is adding a primary key to them ( id
).如果你想让中间表出现在 EF 中,一个可能的“修复”是向它们添加一个主键( id
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.