我在一个群组中有成千上万的联系人(联系人和群组之间存在多对多关系):
public class Group
{
public int GroupID { get; set; }
public string Name { get; set; }
public virtual ICollection<Contact> Contacts { get; set; }
}
public class Contact
{
public int ContactID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public virtual ICollection<Group> Groups { get; set; }
}
当我获取所有联系人时,需要半秒钟。没问题:
context.Contacts.ToList();
我尝试了这个并且花了不到一秒钟:
db.Contacts.SelectMany(s => s.Groups.Where(c => c.GroupID == 1)).ToList();
然而,这需要15秒才能加载(它挂在第二行):
var groups = context.Groups.Include(x => x.Contacts);
foreach(var group in groups)
{
foreach(var contact in group.Contacts)
{
contactsInGroup.Add(contact);
}
}
这里的问题相同(它挂在第四行):
var groups = context.Groups.ToList();
foreach(var group in groups)
{
db.Entry(group).Collection(p => p.Contacts).Load();
foreach(var contact in group.Contacts)
{
contactsInGroup.Add(contact);
}
}
任何人都明白为什么?
答案 0 :(得分:0)
包含()和加载()两者分别加载相关实体 EagerLoading 或 LazyLoading 。
我认为您可以提高性能,在模型中添加索引
public class Group
{
[Index("GroupIdIndex", 1)]
public int GroupID { get; set; }
public string Name { get; set; }
public virtual ICollection<Contact> Contacts { get; set; }
}
public class Contact
{
[Index("ContactIdIndex", 1)]
public int ContactID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public virtual ICollection<Group> Groups { get; set; }
}