It appears that I am getting a concurrency exception on entities that are not modified. I am using Entity Framework 4.3.1, Code First, and this is happening in a WCF service.
To simplify my example, let's assume I have two entities.
public class Foo
{
public int Id { get; set; }
public string BarKey { get; set; }
public string SomeValue { get; set; }
public Bar MyBar { get; set; }
}
public class Bar
{
public string Key { get; set; }
public string OtherValue { get; set; }
public ICollection<Foo> Foos { get; set; }
}
The user can only edit Foos through the application. Bars can be viewed, but not edited. Additionally, I use DTOs with the WCF service. The typical applicaiton flow is as follows.
- Client calls service method
GetFoo
. This will retrieve Foo from the database and map it to a FooDto. This will also retrieve the related Bar and map it to a BarDto. - Client updates FooDto
- Client calls
SaveFoo
and passes in an updated FooDto.
a. The service will re-retrieve the original Foo, usingcontext.Set<Foo>().Find(fooDto.Id)
, then copy the updated values from FooDto.
b. Business logic runs, which may callcontext.Set<Bar>().Find(foo.BarKey)
. Values may be read from Bar, but it will not be updated.
c. The service then callscontext.SaveChanged()
.
At this point I occassionally get a DbUpdateConcurrencyException
. In my error handling, if the exception is of type DbUpdateException
, which is the base class of DbUpdateConcurrencyException
, I loop through ex.Entries
and logentry.Entity.GetType()
and entry.State
.
In my error log I have several entries that show the type is Bar
and the state is Unchanged
. It is entirely possible that Bar
could have been updated. However, I do not care because Bar
is unchanged.
Why am I getting this exception and how to keep it from happening?