![](/img/trans.png)
[英]How can I have a class derived from a class known at runtime implementing an interface known at compilation
[英]How can I use derived class when inherite from an interface
我試圖像這樣創建我的DbContext:
public interface IMyDbContext
{
IQueryable<Product> Products { get; set; }
}
public class MyDbContext: DbContext, IMyDbContext
{
public DbSet<Product> Products { get; set; }
}
我不想在接口中使用IDbSet
,因為該類在另一個不使用EntityFramework的項目中使用。
Visual Studio表示MyDbContext
沒有實現成員IQueryable<Product>
,但是DbSet<Product>
是從IQueryable<Product>
派生的: https : DbSet<Product>
。 113)的.aspx
你能告訴我為什么嗎? 我該如何解決此問題?
非常感謝。
接口實現必須與接口定義完全匹配。 因此,您不能在接口上輸入類型為IQueryable<T>
的屬性,而在類上使用類型為DbSet<T>
屬性來實現它。
使用顯式接口實現來解決此問題:
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; } }
}
如您所見,我從界面中刪除了setter。 那是因為否則您將需要額外的類型檢查,因為有很多實現IQueryable<Product>
的類,但是不能將其分配給DbSet<Product>
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.