Entity Framework modifies collection property with change detection
For performance reasons I have AutoDetectChangesEnabled = false in DbContext.
Updating simple properties and reference properties all works fine, but I'm having problems with collection properties that are multivalued and don't have a union class.
This is a shorthand code trying to add to a collection:
var item = context.Set<Item>().FirstOrDefault();
var category = context.Set<Category>().FirstDefault();
context.Entry(item).Collection(i => i.Categories).CurrentValue.Add(category);
But it does nothing, after SaveChanges the database is the same as it is. Is this the right way to do it?
source to share
I always thought that EF performed DetectChanges
as part of SaveChanges
whatever. But check the source code shows that even then DetectChanges
is not performed when AutoDetectChangesEnabled
there is false
.
I think in your case, the best you can do is override SaveChanges
so that it always detects changes before saving:
public override int SaveChanges()
{
var detectChanges = this.Configuration.AutoDetectChangesEnabled;
try
{
this.Configuration.AutoDetectChangesEnabled = true;
return base.SaveChanges();
}
finally
{
this.Configuration.AutoDetectChangesEnabled = detectChanges;
}
}
An alternative would be to call ChangeTracker.DetectChanges();
in the override, but by setting AutoDetectChangesEnabled = true
, EF itself will choose the moment when to call DetectChanges
at time SaveChanges
, which seems to me preferable.
source to share