[英]How can I use derived class when inherite from an interface
I tried to create my DbContext like this: 我试图像这样创建我的DbContext:
public interface IMyDbContext
{
IQueryable<Product> Products { get; set; }
}
public class MyDbContext: DbContext, IMyDbContext
{
public DbSet<Product> Products { get; set; }
}
I don't want to use IDbSet
in the interface because that class is used in another projects which does not use EntityFramework. 我不想在接口中使用IDbSet
,因为该类在另一个不使用EntityFramework的项目中使用。
Visual Studio said that MyDbContext
does not implement the member IQueryable<Product>
, but DbSet<Product>
is derived from IQueryable<Product>
: https://msdn.microsoft.com/en-us/library/gg696460(v=vs.113).aspx Visual Studio表示MyDbContext
没有实现成员IQueryable<Product>
,但是DbSet<Product>
是从IQueryable<Product>
派生的: https : DbSet<Product>
。 113)的.aspx
Could you please tell me why? 你能告诉我为什么吗? And how can I fix this issue? 我该如何解决此问题?
Thank you a lot. 非常感谢。
Interface implementation has to exactly match the interface definition. 接口实现必须与接口定义完全匹配。 So you can't have a property typed as IQueryable<T>
on the interface and implement it with property typed as DbSet<T>
on the class. 因此,您不能在接口上输入类型为IQueryable<T>
的属性,而在类上使用类型为DbSet<T>
属性来实现它。
Use explicit interface implementation to work around that: 使用显式接口实现来解决此问题:
public interface IMyDbContext
{
IQueryable<Product> Products { get; }
}
public class MyDbContext: DbContext, IMyDbContext
{
public DbSet<Product> Products { get; set; }
IQueryable<Product> IMyDbContext.Products { get { return Products; } }
}
As you can see, I removed the setter from the interface. 如您所见,我从界面中删除了setter。 That's because otherwise you'd need extra type checks, because there is plenty of classes that implement IQueryable<Product>
but can't be assigned to DbSet<Product>
. 那是因为否则您将需要额外的类型检查,因为有很多实现IQueryable<Product>
的类,但是不能将其分配给DbSet<Product>
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.