Question

I'm using Entity Framework 4.3 and DbContext to update my db. I have a collection of Users that permits any user to be modified and then changes saved. My problem is that I'm finding an extra record is being updated unexpectedly when calling SaveChanges().

For example, updating user with pk = 5 to 'revoked' status also generates a sql update for user with pk = 1

SQL profiler trace:

(NOT EXPECTING THIS)

exec sp_executesql N'declare @p int
update [db].[Users]
set @p = 0
where (([UsersPk] = @0) and ([RowVersion] = @1))
select [RowVersion]
from [db].[Users]
where @@ROWCOUNT > 0 and [UsersPk] = @0',N'@0 int,@1 binary(8)',@0=1,@1=0x0000000000011BFD

(EXPECTED)

exec sp_executesql N'update [db].[Users]
set [AccessStatus] = @0
where (([UsersPk] = @1) and ([RowVersion] = @2))
select [RowVersion]
from [db].[Users]
where @@ROWCOUNT > 0 and [UsersPk] = @1',N'@0 varchar(10),@1 int,@2 binary(8)',@0='revoked',@1=5,@2=0x0000000000011C01

To debug this I used this

var mods = DbContext.ChangeTracker.Entries<User>().Where(u => u.State == EntityState.Modified);
Debug.Print(mods.Count().ToString());

to get the number of modified entries which returns 1, but the call to SaveChanges() returns 2, as indeed it should as 2 entries are updated.

I can't figure out why the first query is generated as the properties for this user are not being updated - well they shouldn't be anyway.

I suspect I'm overlooking something fairly straightforward here but can't figure out what. Any suggestions greatly appreciated.

Was it helpful?

Solution

This looks like a bug in .NET 4 that is fixed in the upcoming .NET 4.5 release and for which a fix is also available as a hotfix. The bug shows up on EF 4.3 since it is based on the underlying .NET 4 core libraries.

The details of the hotfix are here: http://support.microsoft.com/kb/2390624

You will need to contact Microsoft Customer Service and Support to obtain the hotfix. However, like I said, the bug is also fixed in .NET 4.5, which will be in beta any day now.

Unfortunately there aren't any good general workarounds.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top