[英]Entity Framework 6 Include missing
我有一個項目使用 Entity Framework 6 為 MVC 項目分成單獨的類。一個類有一個通用接口,然后它被繼承
public interface IRepository<T> where T : class
{
IEnumerable<T> GetAll();
}
繼承如下
public class Repository<T> : IRepository<T> where T : class
{
protected readonly DbContext _context = null;
private readonly DbSet<T> _entities;
public GenericRepository(DbContext context)
{
_context = context;
_entities = _context.Set<T>();
}
public IEnumerable<T> GetAll()
{
return _entities;
}
}
這工作正常,然后我在客戶類中使用它,如下所示
public class CustomerRepository : Repository<Customer>, ICustomerRepository
{
public CustomerRepository(DataContext context) : base(context)
{
}
public List<Customer> GetPremiumCustomers()
{
return GetAll().Where(p => p.Premium).ToList();
}
}
到目前為止一切順利,一切都按預期返回。
我需要包括幾個鏈接到客戶的附加表。
當我去Repository
類並針對_entities
我按. 鍵我看到Include
在菜單中。
然后我進入CustomerRepository
並使用GetAll().
以及沿該行的其他方法,但未顯示Include
?
我嘗試將 using System.Data.Entity
添加到Customer
類的頂部,但這也沒有帶來選項,但它在最頂級的類中可用? 我在這里想念什么?
我試圖實現一些類似的東西
GetAll().Include("Address").Where(p => p.Premium).ToList()
在 Entity Framework 6 中, Include
方法在DbQuery<T>
類上定義( DbSet<T>
派生自DbQuery<T>
)。 另一方面,您的GetAll
方法返回一個IEnumerable<T>
。 編譯器不知道您以IEnumerable<T>
的形式返回DbSet<T>
> ,因此不提供該方法。
如果你想讓GetAll
的調用者使用Include
方法,你可以改變返回類型,例如:
public interface IRepository<T> where T : class
{
DbQuery<T> GetAll();
}
請注意,通過使用DbQuery<T>
作為您的返回類型,界面顯示您正在使用實體框架,並且您不會向界面的用戶隱藏此詳細信息。 為了隱藏這一點,您可以提供另一種接受包含參數並仍返回IEnumerable<T>
的方法:
public interface IRepository<T> where T : class
{
IEnumerable<T> GetAll();
IEnumerable<T> GetAllWithInclude(string include);
}
public class Repository<T> : IRepository<T> where T : class
{
protected readonly DbContext _context = null;
private readonly DbSet<T> _entities;
public GenericRepository(DbContext context)
{
_context = context;
_entities = _context.Set<T>();
}
public IEnumerable<T> GetAll()
{
return _entities;
}
public IEnumerable<T> GetAllWithInclude(string include)
{
return _entities.Include(include);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.