简体   繁体   English

在实体框架中返回 BaseEntity 的 DbSet

[英]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继承的TeacherStudent

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> to DbSet<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 : PersonStudent : 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)但是这样做,您将失去所有实体框架缓存功能( AttachFind等)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM