performance - EF 核心 : How to translate "With table AS"

标签 performance linq entity-framework-core

我正在尝试使用 EF Core 来获取嵌套类别。问题是它太慢了。

看我的代码:

    public async Task<List<Category>> GetNestedCategoryAsync(Category category)
    {
        if (category is null)
            return new List<Category>();

        IQueryable<Category> query = db.Categories.Include(x => x.Childs).Include(x => x.Products).Where(x => category.Childs.Contains(x)).AsNoTracking();

        List<Category> nestedCategories = await query.ToListAsync();

        foreach (Category nestedCategory in nestedCategories.ToArray())
            nestedCategories.AddRange(await GetNestedCategoryAsync(nestedCategory));

        return nestedCategories;
    }

其实我不知道如何将这个 SQL 翻译成 EF .. 甚至可能吗?它的速度快了一千倍
With Categories_CTE As
(
Select *
From Categories
Where Id = 8692

Union All
Select t.*
From Categories t
Inner Join Categories_CTE c On c.Id = t.ParentId
)

Select c.*
From Categories_CTE c;

感谢您的任何提示

最佳答案

Entity Framework 永远不会生成 CTE,这对它来说太过分了。但是,您可以像这样通过 EF Core 使用您的 SQL:

var categories = db.Categories.FromSql("WITH Categories_CTE AS .......");

关于performance - EF 核心 : How to translate "With table AS",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49136487/

相关文章:

php - 使用 PHP 读取大型 excel 文件

sql - LINQ 查询 : SQL-style abbreviations or spell it out?

c# - 如何用表达式调用 SqlFunctions.PatIndex()?

entity-framework - 如何首先在 Entity Framework Core 2.0 代码中按类型继承创建表?

performance - begin-end block 是否会影响条件语句的性能?

python - 在 python 中加速 int 列表到二进制的转换

mysql - 复杂查询的 View 或存储过程?

.net - LINQ Join 运算符是否使用嵌套循环、合并或 HashSet 连接?

asp.net-core - Entity Framework Core 中值对象查询中的额外联接

c# - 在同一个 Asp.Net Core 2 解决方案中将 DbContext 注入(inject)类库项目