最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

entity framework core - Filtering after translation to a non-anonymous type - Stack Overflow

programmeradmin3浏览0评论

If I project to a real type instead of an anonymous type then the filter/sort/page cannot be translated to SQL.

For example

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)

All I can think to do is to rewrite the query as SQL in a view and map it to ItemCategoryWithCount but that's quite a lot of overhead.

Is there a way to get EF to translate querying across a non-anonymous class?

Workaround

Add the query to the 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);
            });
}
发布评论

评论列表(0)

  1. 暂无评论