Entity Framework Attach() 在 Include() 性能之后

本文关键字:性能 之后 Include Framework Entity Attach | 更新日期: 2023-09-27 18:31:46

在急切地加载实体并将其重新附加到单独的上下文中后,我遇到了非常严重的性能问题。

下面是示例。 当公司第一次被收购时,员工就迫不及待地加载了。 有1000名员工。

然后,在

第二个上下文中附加公司需要几秒钟。

Company company;
using(var context = new MyEntities())
{
    company = context
        .Companies
        .Include(x => x.Employees)
        .Single(x => x.CompanyId = someCompanyId);
}
// Stuff happens here
var newEmployee = CreateNewEmployee();
using(var context = new MyEntities())
{
    context.Configuration.AutoDetectChangesEnabled = false;
    context.Companies.Attach(company);  // <<-- Extremely slow
    company.Employees.Add(newEmployee);
    context.SaveChanges();
}

我将如何分离员工列表?

编辑:加载的员工不会有任何变化(除了新添加的)

Entity Framework Attach() 在 Include() 性能之后

关闭自动检测更改

context.Configuration.AutoDetectChangesEnabled = false;