I am using Entity Framework through a Repositories pattern and have a significant and surprising performance problem. I have done profiling so I have a pretty good idea of what happens, I just don’t know what to do about it.
Here is the essense of my code (simplified):
var employee = Repositories.Employees.FirstOrDefault(s => s.EmployeeId == employeeId);
employee.CompanyId = null;
Repositories.Commit();
The middle line (employee.CompanyId = null) takes an astounding amount of time to complete (around 30 seconds). The time is NOT spent on the Commit line.
Through profiling, I have found the reason to be running this part of the auto generated EF code:
if (previousValue != null && previousValue.**Employees**.Contains(this))
{
previousValue.Employees.Remove(this);
}
That doesn’t really help me, but it does confirm that the problem lies in the EF. I would really like to know what to do. I can update the column in other ways (stored procedure) but I would really rather use the EF everywhere.
I cannot easily edit the EF settings, so I would prefer suggestions that does not involve this.
Update
I solved the problem by running SQL directly against the database and then refreshing the object from context to make sure EF would detect this change immediately.
public void SetCompanyNull(Guid employeeId)
{
_ctx.ExecuteStoreCommand("UPDATE Employee SET CompanyId = NULL WHERE EmployeeId = N'" + employeeId + "'");
_ctx.Refresh(RefreshMode.StoreWins, _ctx.Employees.FirstOrDefault(s => s.EmployeeId == employeeId));
}
Update 2
I ALSO solved the problem by disabling lazy loading temporarily.
var lazyLoadDisabled = false;
if (_ctx.ContextOptions.LazyLoadingEnabled)
{
_ctx.ContextOptions.LazyLoadingEnabled = false;
lazyLoadDisabled = true;
}
this.GetEmployeeById(employeeId).CompanyId = null;
this.SaveChanges();
if (lazyLoadDisabled)
{
_ctx.ContextOptions.LazyLoadingEnabled = true;
}
I am really curious about WHY it’s so much faster with lazy loading disabled (and which side-effects this might have)
This is problem in EF POCO Generator Template which causes unexpected lazy loading in some scenarios. This template generates fixup code for navigation properties so if you change the navigation property on one side it internally goes to other end of the changed relation and tries to fix the relation to be still consistent. Unfortunately if your related object doesn’t have navigation property loaded it triggers lazy loading.
What you can do:
Employees) from yourCompanycontext.ContextOptions.LazyLoadingEnabled = false