I have a Category
object and a Product
object. They have a many-to-many relationship, so the CategoryProduct
table gets created when the database gets initialized. In the OnModelCreating
method I have the following code to map the relationship
modelBuilder.Entity<Category>()
.HasMany( c => c.Products )
.WithMany( i => i.Categories )
.Map( t => t.MapLeftKey( "CategoryId" )
.MapRightKey( "ProductId" )
.ToTable( "CategoryProducts" ));
The CategoryProducts
table gets loaded correctly and everything's good. But when I am actually debugging the site, it takes an extremely long time to navigate to a category. For example, there is an 'Accessories' category that has over 1400 products. The code will grab everything for the category selected, but it will lazy load the products when it needs them. When it is lazy loading the products is when it takes the long time ( obviously ). I need to know how I can speed this up. Does anyone have any suggestions?
Thanks a lot
EDIT: Here are the Category
and Product
classes
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; }
}
EDIT: Code doing the query
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;
}
}