2013-04-12 70 views
2

我有這個設置,並得到一個編譯器警告「......隱藏繼承成員...」。我該如何解決?C#隱藏繼承成員

public interface IRepository<T> where T : class 
{ 
    IQueryable<T> GetAll(); 
    T GetById(int id); 
} 

public class EFRepository<T> : IRepository<T> where T : class 
{ 
    public EFRepository(DbContext dbContext) 
    { 
     if (dbContext == null) 
      throw new ArgumentNullException("dbContext"); 
     DbContext = dbContext; 
     DbSet = DbContext.Set<T>(); 
    } 

    protected DbContext DbContext { get; set; } 

    protected DbSet<T> DbSet { get; set; } 

    public virtual IQueryable<T> GetAll() 
    { 
     return DbSet; 
    } 

    public virtual T GetById(int id) 
    { 
     return DbSet.Find(id); 
    } 

} 

public interface IProductRepository : IRepository<Product> 
{ 
    // Product specific interface code here 
} 

public class ProductRepository : EFRepository<Product>, IProductRepository 
{ 
    public ProductRepository(DbContext context) : base(context) { } 

    public IQueryable<Product> GetAll() 
    { 
     return DbSet.Include("Table1").Include("Table2").AsQueryable(); 
    } 
} 

我得到的編譯器警告消息,但在運行應用程序時,我得到一個StackOverflowException錯誤。添加新關鍵字仍會生成StackOverflowException錯誤。覆蓋關鍵字不起作用。如果我註釋掉ProductRepositoryGetAll()方法,一切都很好,並且很棒。但我需要重寫GetAll()方法。

謝謝。

+3

你是什麼意思「override關鍵字不工作」? – TheNextman

+1

我認爲你需要'new'關鍵字,而不是覆蓋。 – Felix

+0

如果您將GetAll()標記爲基類中的虛擬對象,然後使用override關鍵字將其覆蓋到子類中,則方法重寫應該可以工作。你是什​​麼意思,它「不起作用」?細節?你也可以提供關於拋出異常的更多信息嗎? – spy890

回答

3

馬克ProductRepository.GetAll與 「新」 的文章:

public new IQueryable<Product> GetAll() 
{ 
    return DbSet.Include("Table1").Include("Table2").AsQueryable(); 
} 

這將隱藏方法EFRepository.GetAll()。

您也可以選擇重寫基方法,如果你想這兩種方法返回相同的結果:

public override IQueryable<Product> GetAll() 
{ 
    return DbSet.Include("Table1").Include("Table2").AsQueryable(); 
}