[英]Return DbSet of BaseEntity in Entity Framework
Is it possible to return DbSet<BaseEntity>
form a method in Entity Framework using table per concrete type inheritance or other inheritance type?是否可以使用每个具体类型继承或其他继承类型的表返回
DbSet<BaseEntity>
形成实体框架中的方法?
Teacher
and Student
inherited from Person
.从
Person
继承的Teacher
和Student
。
DbSet<Teacher> Teachers;
DbSet<Student> Students;
DbSet<Person> GetGenericDbSet(int entityType)
{
if (entityType == 0)
{
return Teachers;
}
else
{
return Students;
}
}
Compile error:编译错误:
Cannot implicitly convert type
DbSet<Teacher>
toDbSet<Person>
不能将类型
DbSet<Teacher>
隐式转换为DbSet<Person>
Even if Teacher : Person
and Student : Person
, you can't return a DbSet<Teacher>
as a DbSet<Person>
because IDbSet<T>
is not covariant (it looks like even if the base interface IQueryable
is covariant, its child interface does not keep that property).即使
Teacher : Person
和Student : Person
也不能返回DbSet<Teacher>
作为DbSet<Person>
因为IDbSet<T>
不是协变的(看起来即使基接口IQueryable
是协变的,它的子接口不保留该财产)。
Another solution would be to change the return type of your method to IQueryable<Person>
(as IQueryable<T>
is covariant, it will accept an object with a child class of T
):另一种解决方案是将方法的返回类型更改为
IQueryable<Person>
(因为IQueryable<T>
是协变的,它将接受具有T
子类的对象):
IQueryable<Person> GetPerson(int type)
{
if (type == 0)
{
return Teachers.Cast<Person>();
}
else
{
return Students.Cast<Person>();
}
}
But doing this, you will lose all the Entity Framework Cache capabilities ( Attach
, Find
, etc)但是这样做,您将失去所有实体框架缓存功能(
Attach
、 Find
等)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.