简体   繁体   English

EF Core - 多对多关系查询非常慢

[英]EF Core - Query with many to many relationship very slow

I want to do a "simple" query with Entity Framework Core that involves a many to many relationship.我想对涉及多对多关系的 Entity Framework Core 进行“简单”查询。

Currently the execution time of the query is very slow because most of it seems to be run locally.目前查询的执行时间很慢,因为它大部分似乎是在本地运行的。 I get the following warnings in my logs:我在日志中收到以下警告:

 The LINQ expression 'where ([categoryId] == [categoryRelationEntity].CategoryId)' could not be translated and will be evaluated locally.
 The LINQ expression 'Any()' could not be translated and will be evaluated locally.
 ...

The warnings basically tell me that nothing could be done in SQL and everything was done locally.警告基本上告诉我,在 SQL 中什么也做不了,一切都在本地完成。

Here is my query in LINQ:这是我在 LINQ 中的查询:

var categoryIds = new int[] { 1 , 2 , 3 };
var result = await _dbSet // MyTable
                    .Include(x => x.Categories) // CategoriesRelation
                    .ThenInclude(x => x.CategoryEntity)
                    .AsNoTracking()
                    .Where(x=>  x.Categories
                        .All(categoryRelationEntity => categoryIds.Any(categoryId => categoryId == categoryRelationEntity.CategoryId)))
                    .ToListAsync();

If I write the SQL myself it should look like this:如果我自己编写 SQL,它应该如下所示:

SELECT * FROM MyTable
LEFT OUTER JOIN CategoriesRelation ON MyTable.Id = CategoriesRelation.MyTableId
WHERE "CategoryId" IN (1,2,3)

Is something wrong with how I wrote my LINQ?我写 LINQ 的方式有问题吗? I did some research and all resources that I found suggested I had to do All() and Any().我做了一些研究,发现的所有资源都表明我必须执行 All() 和 Any()。

I tried many different things and nothing worked... I'm so frustrated that I'm very close to just writing it in raw sql...我尝试了很多不同的东西,但没有任何效果......我很沮丧,以至于我非常接近只用原始 sql 编写它......

尝试使用categoryIds.Contains(categoryId)方法代替.Any()

Download Z.EntityFramework.Plus.EFCore from nuget.从 nuget 下载 Z.EntityFramework.Plus.EFCore。 ToListAsync() causes slower performance. ToListAsync() 会导致性能下降。 Use AsQueryableAsync() instead for better performance.改用 AsQueryableAsync() 以获得更好的性能。 And use code below并使用下面的代码

var result = await _dbSet
                   .IncludeFilter(x => x.Categories.Where(x => categoryIds.Contains(x.categoryId)))
                   .ThenInclude(x => x.CategoryEntity).AsQueryableAsync();

在此处输入图片说明

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

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