我正在使用Entity Framework和一个大型数据库(由200多个表组成)。
试图创建一个返回的泛型方法 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必须是引用类型)它在类型方面可能会超出预期(基于 在此)。
当我尝试实际调用具有特定类型的方法时,会出现问题。
[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
)使它无用。