实体框架6包括缺失



我有一个项目分解成使用实体框架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我按下键i看到菜单中的Include

然后我进入CustomerRepository并对GetAll().和沿着这条线的其他方法做同样的事情,但Include没有显示?

我尝试使用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);
}
}

最新更新