在Include()性能之后的实体框架Attach()

时间:2013-09-17 06:39:42

标签: c# .net performance entity-framework entity-framework-5

eagerly loading实体之后并在单独的上下文中重新附加它,我遇到了非常严重的性能问题。

以下示例。公司首次获取时,员工急切地加载。有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();
}

我如何分离员工名单?

编辑:加载的员工不会有任何更改(新增加的除外)

1 个答案:

答案 0 :(得分:0)

关闭AutoDetectChanges

context.Configuration.AutoDetectChangesEnabled = false;