[英]Entity Framework Generic Inheritance
I'm trying to assign a DbSet
of class that is inherited from a more generic class. 我试图分配从更通用的类继承的
DbSet
类。 The example below demonstrates what I'm trying to achieve: 下面的示例演示了我要实现的目标:
DbSet<Animal> dbSet;
switch (selectedAnimal)
{
case "Dog":
dbSet = _Context.Dog; // DbSet<Dog>
break;
case "Cat":
dbSet = _Context.Cat; // DbSet<Cat>
break;
case "Pig":
dbSet = _Context.Pig; // DbSet<Pig>
break;
}
The Dog
, Cat
, Pig
class is an inherited class of Animal
, as follows: Dog
, Cat
, Pig
类是Animal
的继承类,如下所示:
public class Dog : Animal { }
But I am getting a compile-time error of Cannot implicitly convert type DbSet<Dog> to DbSet<Animal>
但是我遇到了
Cannot implicitly convert type DbSet<Dog> to DbSet<Animal>
的编译时错误
How can I implement my design without getting the error? 如何在没有错误的情况下实现我的设计?
PS The code above is just to illustrate what I'm trying to achieve, so forgive me if it doesn't make sense. PS上面的代码只是为了说明我要实现的目标,请原谅我,如果这样做没有意义。
Because compiler cant cast derived classes to base class w/o information loss. 因为编译器无法将派生类强制转换为基类而没有信息丢失。 You simply cant put DbSet of Cat into DbSet of Animal where Cat : Animal
您根本无法将Cat的DbSet放入Animal的DbSet中,其中Cat:Animal
But you CAN put DbSet of Animal into DbSet of Cat 但是您可以将动物的DbSet放入猫的DbSet中
Try this one: 试试这个:
var dbSet = GetDbSet(selectedObject) //selectedObject is Cat,Dog,Pig whatever
And the method: 和方法:
private DbSet<T> GetDbSet<T>(T selectedAnimal) where T : Animal
{
return this.Set<T>(); //this == EF Context
}
What you're referring to is called covariance. 您所指的就是协方差。 In C# only interfaces can be covariant.
在C#中,仅接口可以是协变的。 So
IEnumerable<Cat>
is a subtype of IEnumerable<Animal>
. 因此
IEnumerable<Cat>
是IEnumerable<Animal>
的子类型。 The problem with declaring a DbSet<Animal>
and then putting a variable of type DbSet<Cat>
in it is that a variable of type DbSet<Animal>
has methods that allow, for instance, adding an Animal
entity. 与声明一个问题
DbSet<Animal>
然后把类型的变量DbSet<Cat>
在它是类型的变量DbSet<Animal>
具有允许,例如方法,添加Animal
实体。 That Animal
might be a Dog
. 那
Animal
可能是Dog
。 But the variable you put in there was a DbSet<Cat>
and that can't contain Dog
. 但是您在其中输入的变量是
DbSet<Cat>
,并且不能包含Dog
。 It would be a violation of strong typing. 这将违反强类型输入。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.