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

Entity Framework Core:如何通过代码动态选择对应DbSet?

问题

我希望根据请求参数指定_context要操作的数据表。我的_context中有Chair、Table这两个数据表对应的实体类,它们均实现了IProduct接口。我想要编写一个函数,能够返回DbSet<Chair>或DbSet<Table>。

经过两小时的搜索,我仍未找到实现方法。我的其中一次尝试代码如下:

public DbSet<IProduct> GetDbSet(bool condition)
{
  if (condition)
     {
          return _context.Set<Chair>();
     }
 else
     {
         return _context.Set<Table>();
     }
}

这段代码报错:无法将Chair隐式转换为IProduct。我是C#新手,相信一定有简单的实现方式,但几乎要放弃寻找了。

可行解决方案

更新:根据建议,将扩展方法的类型改为IQueryable。

将查询逻辑封装到IQueryable的扩展方法中,再根据条件调用对应实体的DbSet方法即可。示例代码如下(省略实际查询逻辑):

public static class IQueryableExtensions
{
  public static decimal GetTotalSales<T>(this IQueryable<T> dbSet) where T: class, IProduct
  {
     var result = dbSet
                  .Where(...)
                  .Sum(x => (decimal)x.Sales);   
     return result;
  }
}

调用示例:

if (condition)
{ 
     return _context.Chair.GetTotalSales();
}
else{ 
     return _context.Table.GetTotalSales();
}

(注:原代码中_context.Book应为笔误,修正为_context.Table)

内容的提问来源于stack exchange,提问作者Alex S.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 01:52:17