1

我有一个Category对象和一个Product对象。它们具有多对多关系,因此在CategoryProduct初始化数据库时会创建表。在OnModelCreating方法中,我有以下代码来映射关系

modelBuilder.Entity<Category>()
    .HasMany( c => c.Products )
    .WithMany( i => i.Categories )
    .Map( t => t.MapLeftKey( "CategoryId" )
    .MapRightKey( "ProductId" )
    .ToTable( "CategoryProducts" ));

CategoryProducts被正确加载,一切都很好。但是当我实际调试站点时,导航到一个类别需要很长时间。例如,有一个包含 1400 多种产品的“配件”类别。该代码将获取所选类别的所有内容,但它会在需要时延迟加载产品。延迟加载产品时需要很长时间(显然)。我需要知道如何加快速度。有没有人有什么建议?

非常感谢

编辑:这是CategoryProduct

public class Category : WebPage
    {
        private int _count = -1;
        public bool IsFeatured { get; set; }
        public virtual Category Parent { get; set; }

        public virtual List<Category> Children { get; set; }
        public virtual List<Product> Products { get; set; }    
        public virtual List<Discount> Discounts { get; set; }
}

public class Product : WebPage
    {
        public string Sku { get; set; }
        public string Details { get; set; }
        public string AdditionalDetails { get; set; }    

        public virtual List<Category> Categories { get; set; }
        public virtual Brand Brand { get; set; }
}

编辑:执行查询的代码

public virtual IEnumerable<TEntity> Get(
            Expression<Func<TEntity, bool>> filter = null,
            Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
            string includeProperties = "", int? limit = null)
        {
            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 (limit != null && limit.HasValue && limit.GetValueOrDefault() > 0)
            {
                query = query.Take(limit.Value);
            }

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

1 回答 1

2

我想象你Get<Category>(x => x.SomeName == "abcdef")和产品的迭代。

不能Get<Product>(x => x.Categories.Where(y => y.SomeName == "abcdef").Count() > 0)吗?

于 2013-01-28T17:05:00.597 回答