我有一个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 多种产品的“配件”类别。该代码将获取所选类别的所有内容,但它会在需要时延迟加载产品。延迟加载产品时需要很长时间(显然)。我需要知道如何加快速度。有没有人有什么建议?
非常感谢
编辑:这是Category
和Product
类
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;
}
}