简体   繁体   English

如何使用LINQ和Entity Framework查询与“AND”条件的多对多关系

[英]How to query many-to-many relationship with 'AND' condition using LINQ and Entity Framework

My current database solution includes three tables called Establishment , Feature , and a linking many-to-many table called EstablishmentFeature (since an establishment can have many features, and a feature can exists across multiple establishments). 我当前的数据库解决方案包括三个名为EstablishmentFeature表,以及一个名为EstablishmentFeature的多对多表链接(因为一个企业可以拥有许多功能,并且一个功能可以存在于多个企业中)。

I need to generate a query that returns establishments that meet only certain criteria, namely, which establishments have X features based on a collection of featureId's being passed in. The establishment must have ALL features that are being search, ie. 我需要生成一个返回只满足某些条件的企业的查询,即哪些企业具有基于传入的featureId集合的X特征。企业必须拥有正在搜索的所有功能,即。 AND not OR condition. AND没有OR条件。

I got the SQL to achieve the desired result, but I am pulling my hair out trying to work out the LINQ (lambra prefereably) equivalent. 我得到了SQL以达到理想的结果,但是我想把我的头发拉出来试图找出LINQ(lambra)。 The T-SQL is: T-SQL是:

SELECT e.[EstablishmentId], e.[Name], e.[Description]
FROM Establishment e
INNER JOIN EstablishmentFeature ef
ON e.[EstablishmentId] = ef.[EstablishmentId]
WHERE ef.[FeatureId]  in ('20', '15', '72')
GROUP BY e.[EstablishmentId], e.[Name], e.[Description] 
HAVING COUNT(*) = 3

I tried to use Linqer to convert the SQL but Linqer crashes when it attempts the conversion. 我尝试使用Linqer转换SQL,但Linqer在尝试转换时崩溃。 I tried reinstalling Linqer, but it crashes without fail when trying to compile the LINQ syntax. 我尝试重新安装Linqer,但在尝试编译LINQ语法时崩溃没有失败。 (Simpler conversions work though). (虽然更简单的转换工作)。 Also tried to work out the LINQ equivalent using LinqPad, but I just ended up chasing my tail... 还尝试使用LinqPad计算出LINQ等价物,但我最后还是追逐了我的尾巴......

Is this something I will have to use PredicateBuilder for? 这是我必须使用PredicateBuilder吗? Somewhat exhausted, I don't want to go through the PredicateBuilder learning curve if there is a simple solution that is escaping me. 有点筋疲力尽,如果有一个简单的解决方案可以逃避我,我不想通过PredicateBuilder学习曲线。

I'd try this (For all given ids there is any (= at least one) feature that has this given id): 我试试这个(对于所有给定的id,有任何 (=至少一个)具有此给定id的特征):

var establishments = context.Establishments
    .Where(e => featureIds.All(fid => e.Features.Any(f => f.FeatureId == fid)))
    .ToList();

( featureIds is an IEnumerable<int> with the Ids being searched for.) featureIds是一个IEnumerable<int> ,正在搜索ID。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM