You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

EF投影至非匿名类型后,过滤/排序/分页无法转SQL的解决方案问询

问题:Entity Framework投影到具体类型时,过滤/排序/分页无法转换为SQL语句

当在Entity Framework中将查询投影到具体类型(而非匿名类型)时,过滤、排序、分页操作无法被转换为SQL语句。示例代码如下:

IQueryable<ItemCategoryWithCount> data = db.ItemCategories
    .Join(db.ItemSpecifications, z => z.CategoryId, z => z.ItemCategoryId, (ItemCategory c, ItemSpecification s) => new { ItemCategory = c, Item = s })
    .GroupBy(z => z.ItemCategory)
    .Select(z => new ItemCategoryWithCount(z.Key, z.Count()))
    //.ToList(/* Apply(options) doesn't transpile to SQL which makes it useless. */).AsQueryable()
    .Apply(gridOptions)

目前我能想到的办法是将查询改写为SQL视图并映射到ItemCategoryWithCount,但这种方式开销较大。请问是否有办法让EF支持对非匿名类的查询转换?

临时解决方案

将查询添加至DbContext:

public DbSet<ItemCategoryWithCount> Hack { get; set; }

protected override void OnModelCreating(ModelBuilder builder)
{
            builder.Entity<ItemCategoryWithCount>(e =>
            {
                e.ToSqlQuery(@"
SELECT c.*, COUNT(*) AS Count 
FROM ItemCategories c 
    INNER JOIN ItemSpecifications i ON i.ItemCategoryId = c.CategoryId 
GROUP BY c.CategoryId, c.ParentCategoryId, c.CategoryName
");
                e.HasBaseType((string)null);
            });
}

内容的提问来源于stack exchange,提问作者Richard Barraclough

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 19:22:03