我在大型数据库(由 200 多个表组成)中使用 Entity Framework 。
尝试创建一个返回 DbSet<T>
的通用方法特定表的 T
(即类,可以是 TableA
)。
使用实体数据模型(自动)创建的实体类如下所示:
public partial class sqlEntities : DbContext
{
public virtual DbSet<TableA> TableA { get; set; }
public virtual DbSet<TableB> TableB { get; set; }
public virtual DbSet<TableC> TableC { get; set; }
... // other methods
}
我的主类是这样的
public class TableModifier
{
// Should return first 10 elements from a table of that type T
public IQueryable<T> GetFromDatabase<T>() where T : EntityObject
{
try
{
using (sqlEntities ctx = new sqlEntities())
{
// Get the DbSet of the type T from the entities model (i.e. DB)
DbSet<T> dbSet = ctx.Set<T>();
return dbSet.Take(10);
}
}
catch (Exception ex)
{
// Invalid type was provided (i.e. table does not exist in database)
throw new ArgumentException("Invalid Entity", ex);
}
}
... // other methods
}
我必须设置约束 where T : EntityObject
在 T
在 EntityObject
内界限。如果没有这样的约束,那么 DbSet<T> dbSet
会提示(即 T 必须是引用类型)它在类型方面可能比预期的要多(关于此的 based)。
当我尝试实际调用具有特定类型的方法时出现问题。
[TestMethod]
public void Test_GetTest()
{
TableModifier t_modifier = new TableModifier();
// The get method now only accepts types of type EntityObject
IQueryable<TableA> i_q = t_modifier.GetFromDatabase<TableA>();
}
报错:
There is no implicit reference conversion from 'TableMod.TableA' to
'System.Data.Entity.Core.Objects.DataClasses.EntityObject'.
我如何(转换?)TableA
输入 EntityObject
如果我知道它存在于那个实体模型?
虽然这是不正确的语法(和逻辑),但这正是我所追求的:
t_modifier.GetFromDatabase<(EntityObject)TableA>();
如何定义 TableA
(连同所有其他 200 个表)键入成为 EntityObject
的一部分?
一个潜在的解决方案
原来我的约束太具体了,我需要更改的是 where T : IEntity
到
where T : class
所以 T
DbSet<T>
是什么最初预期,一个类类型
省去了必须向 200 多个表类添加实现的麻烦,TableA
, TableB
, ...
当然还有其他问题,例如从 IQueryable<T>
更改返回类型至 List<T>
自 IQueryable
否则将在 DbContext
的范围之外返回(即 sqlEntities
)使其无用。
最佳答案
为什么不尝试将约束更改为类而不是 EntityObject
public IQueryable<T> GetFromDatabase<T>() where T : class
关于c# - 从 DbContext 检索 DbSet<T> 的通用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24626844/