Is it possible to return DbSet<BaseEntity>
form a method in Entity Framework using table per concrete type inheritance or other inheritance type?
Teacher
and Student
inherited from Person
.
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>
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).
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> 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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.