Mar 9, 2015 at 5:28 PM
Edited Mar 9, 2015 at 10:22 PM
I have 2 classes:
Each log has a LogSeverity.
When I start my application, I get all LogSeverity with .AsNoTracking() as I create a Unit of Work and Context each time I need to call the database. I have "using" everywhere in order to keep my context, UoW and services open the sortest time possible.
When I save logs, I sometimes get the following error:
Saving or accepting changes failed because more than one entity of type 'Entities.Models.LogSeverity' have the same primary key value. Ensure that explicitly set primary key values are unique. Ensure that database-generated primary keys are configured correctly in the database and in the Entity Framework model. Use the Entity Designer for Database First/Model First configuration. Use the 'HasDatabaseGeneratedOption" fluent API or 'DatabaseGeneratedAttribute' for Code First configuration.
The error pops in this code from DataContext.cs
private void SyncObjectsStatePreCommit()
foreach (var dbEntityEntry in ChangeTracker.Entries())
dbEntityEntry.State = StateHelper.ConvertState(((IObjectState)dbEntityEntry.Entity).ObjectState);
I am using a Code First approach and added the needed line in my Mapping to make sure it was ok:
this.Property(t => t.Id).HasColumnName("Id").HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
After a lot of investigation, I found that despite setting the ObjecState to "Unchanged", it looks like it's not added correctly when entities are added to the ChangeTracker.Entries().
I can now see a specific LogServerity added twice. The first one has a State of "Added" while the second one has a state of "Unchanged". This is for the same LogSeverity (same object, same Id).
How can it be added multiple times ? Is there a way to valide the entities before adding them to the ChangeTracker ?
My guess is that the bugs comes up at this line because the framework tries to set the state to "Unchanged" and it "maybe" cause a problem to have 2 identical entities with the same status, no ?
The code runs fine when called from a console app. But when called from a MVC controller, the bug occurs.