EF Core:如何翻译“With table AS”

问题描述 投票:3回答:1

我正在尝试使用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;

谢谢你的任何提示

performance linq entity-framework-core
1个回答
2
投票

实体框架永远不会产生CTE,这对它来说太过分了。但是,您可以通过EF Core使用SQL,如下所示:

var categories = db.Categories.FromSql("WITH Categories_CTE AS .......");
© www.soinside.com 2019 - 2024. All rights reserved.