简体   繁体   English

Linq加入实体无法计数

[英]Linq join enumerable with entity

I have a an entity let's say call it Blog . 我有一个实体,可以称其为Blog Each Blog entity has many Keyword . 每个Blog实体都有许多Keyword The 2 are related via an fk on the keyword table. 2通过关键字表上的fk相关联。

I have a query with a signature like this FindAllBlogByKeywords(IEnumerable<string> keywords) 我有一个带有这样的签名的查询FindAllBlogByKeywords(IEnumerable<string> keywords)

How would I write a linq query to pull any blog that matches ALL of the keywords in the parameter. 我将如何编写linq查询以拉出与参数中所有关键字匹配的任何博客。

The problem is EF is not allowing a join between enumerable and tables. 问题是EF不允许可枚举和表之间的联接。 It's not contains either because I want the query to match ALL keywords, not just any one - besides I have 2 keywords list, I need the keyword in the parameter to be a subset of the keywords in the persistence. 它也不包含,因为我希望查询匹配所有关键字,而不仅仅是任何一个-除了2个关键字列表之外,我还需要参数中的关键字作为持久性中关键字的子集。

You can add .Where clauses for each keyword: 您可以为每个关键字添加.Where子句:

IEnumerable<Blog> FindAllBlogByKeywords(IEnumerable<string> keywords)
{
     IQueryable<Blog> query = context.Blogs;

     foreach(string key in keywords)
         query = query.Where(blog => blog.Keywords.Contains(key));

     // Execute query (optional)
     return query.ToList();
}

This works because the query execution is deferred until the end. 之所以可行,是因为查询执行被推迟到最后。 By chaining multiple .Where clauses, you effectively create an "ALL" statement. 通过链接多个.Where子句,可以有效地创建“ ALL”语句。

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

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