简体   繁体   English

LINQ无法从实体框架中检索相关数据

[英]LINQ Unable to retrieve related data from entity framework

I have the following: 我有以下内容:

db.Products.Where(p=>p.Sectors.Where(s=>s.website_id == websiteObj.website_id)).Count();

websiteObj is not null and has valid data. websiteObj不为null且具有有效数据。 There is a many to many relationship between products and sectors. 产品和行业之间存在多种关系。 Also, there is a 1 to many relationship between sectors and websites. 此外,部门和网站之间存在一对多的关系。 I don't have direct access to products from website, I have to go through the website related sectors. 我没有从网站直接访问产品,我必须通过网站相关部门。

Anyway, this example works: db.Sectors.Where(p=>p.website_id == websiteObj.website_id)).Count(); 无论如何,这个例子有效: db.Sectors.Where(p=>p.website_id == websiteObj.website_id)).Count();

But the issue is that the first LINQ query gives me the following errors: Delegate 'System.Func<BusinessObjects.Product,int,bool>' does not take 1 arguments. 但问题是第一个LINQ查询给出了以下错误: Delegate 'System.Func<BusinessObjects.Product,int,bool>' does not take 1 arguments. Cannot convert lambda expression to type 'string' because it is not a delegate type.

And a couple other errors. 还有其他一些错误。

Anyway, what am I doing wrong? 无论如何,我做错了什么? This is my first attempt with LINQ. 这是我第一次使用LINQ。 Thanks in advance. 提前致谢。

I think you need Any in the inner query: 我认为你在内部查询中需要Any

db.Products.Where(p => p.Sectors.Any(s => s.website_id == websiteObj.website_id))
           .Count();

This would return all Products with at least one sector with the specified website_id. 这将返回具有至少一个具有指定website_id的扇区的所有产品。

If you want all Products where all sectors belong to the specified website_id, simply use All instead of Any : 如果你想去的地方各界属于指定website_id所有产品,简单地使用All的,而不是Any

db.Products.Where(p => p.Sectors.All(s => s.website_id == websiteObj.website_id))
           .Count();

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

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