EF Core:如何翻译"使用表AS"

时间:2018-03-06 17:15:33

标签: 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;

感谢您提供任何提示

1 个答案:

答案 0 :(得分:2)

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

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