我如何使 .Include 在 IEnumerable 上工作

2024-01-15

我在存储库上运行查询时遇到问题。我必须通过 id 获取产品并将其与产品图像一起显示在编辑视图中。

我的 ProductRepository 中有一个方法实现 Get() ,即获取所有产品和 GetByID ,顾名思义。我使用如下所示的工作单元类实现了通用存储库模式

public class GenericRepository<TEntity> where TEntity : class
    {
        internal SchoolContext context;
        internal DbSet<TEntity> dbSet;

        public GenericRepository(SchoolContext context)
        {
            this.context = context;
            this.dbSet = context.Set<TEntity>();
        }

        public virtual IEnumerable<TEntity> Get(
            Expression<Func<TEntity, bool>> filter = null,
            Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
            string includeProperties = "")
        {
            IQueryable<TEntity> query = dbSet;

            if (filter != null)
            {
                query = query.Where(filter);
            }

            foreach (var includeProperty in includeProperties.Split
                (new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
            {
                query = query.Include(includeProperty);
            }

            if (orderBy != null)
            {
                return orderBy(query).ToList();
            }
            else
            {
                return query.ToList();
            }
        }

        public virtual TEntity GetByID(object id)
        {
            return dbSet.Find(id);
        }

我认为这是唯一相关的代码块。当我尝试运行在教程中找到的查询来使用下面的查询获取图像旁边的产品时,问题就出现了

Product product = db.Products.Include(s => s.Files).SingleOrDefault(s => s.ID == id);

我无法使用 db.Products 因为我正在使用工作单元类,所以我必须使用以下命令运行查询_unit.ProductRepository.GetByID().Include(s => s.Files).SingleOrDefault(s => s.ID == id);

然而,这似乎不可能,我被困住了。


您不能将 Include 与 IEnumerable 一起使用,它仅适用于 IQueryable,当您在存储库中调用时query.ToList();您的查询是在 IEnumerable 中从数据库检索到内存的,当您的数据在内存中时, Include 不起作用。

您可以将要包含在查询中的对象作为参数传递,就像在 Get 方法中使用过滤器或订单一样。

您可以重写 ProductRepository 方法

    public override Product GetByID(object ID)
    {
        return db.Products.Include(p => p.Files).SingleOrDefault(p => p.ID == ID);
    }

或者如果您不想总是返回文件

    public override Product GetByID(object ID, List<string> includes)
    {

        var query = db.Products.AsQueryable();
        foreach (string include in includes)
        {
            query = query.Include(include);
       }

       return query.SingleOrDefault(p => p.ID == ID);
    }

并调用像

 Product product = new ProductRepository().GetByID(IDProduct, new List<string>() { "Files" });
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

我如何使 .Include 在 IEnumerable 上工作 的相关文章

随机推荐