简体   繁体   English

实体框架非常慢

[英]Entity Framework Very Slow

I have thousands of contacts in just one group (contacts and groups have a many-to-many relationship) : 我仅在一组中有数千个联系人(联系人和组具有多对多关系):

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; }
}

When I fetch all the contacts, it takes half a second. 当我获取所有联系人时,需要半秒钟。 No problem : 没问题 :

context.Contacts.ToList();

I tried this and it took again less than a second : 我尝试了一下,又花了不到一秒钟的时间:

 db.Contacts.SelectMany(s => s.Groups.Where(c => c.GroupID == 1)).ToList();

However, this took 15 seconds to load (it hangs on the second line) : 但是,这花费了15秒的时间加载(挂在第二行):

var groups = context.Groups.Include(x => x.Contacts);
foreach(var group in groups)
{
     foreach(var contact in group.Contacts)
     {
         contactsInGroup.Add(contact);
     }
}

Same problem here (it hangs on the fourth line) : 同样的问题在这里(它挂在第四行):

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);
     }
}

Anybody understand why ? 有人知道为什么吗?

Include() and Load() both to load related entities EagerLoading or LazyLoading respectively. 包括()负载()都加载相关实体分别惰性加载 EagerLoading或。

I think you can improve your performance to add index in your model 我认为您可以提高性能以在模型中添加索引

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; }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM