Entity Framework 5 and ValidateOnSaveEnabled

I have just started a new project and having had previous happy times with Entity Framework, I Nuget’ed in the latest version. All was going well until I tried to update an entity. I have the following code;

using (var c = new EFContext()) 
{
Data.User u = new Data.User() { UserId = UserId };
c
.Users.Attach(u);
u
.FailedPasswordAttemptCount = newFailedPasswordAttemptCount;
c
.SaveChanges();
}

In EF4, my understanding is that this would send an update statement to the database and only the FailedPasswordAttemptCount would be incremented for the user with the corresponding UserId.

In EF5, this craps out with a DbEntityValidationException as I have a non-nullable field in the user table (UserName).

I could solve this by creating my Data.User object with an empty UserName,

using (var c = new EFContext())
{
Data.User u = new Data.User() { UserId = UserId, UserName = "" };
...
c
.Entry(u).Property("FailedPasswordAttemptCount ").IsModified = true;
...
}

but this doesn’t seem particularly manageable as more non-nullable fields are added to this and numerous other tables.

It turns out there is now a property in EF called ValidateOnSaveEnabled ValidateOnSaveEnabled is a boolean which determines if entities should be validated automatically when SaveChanges() is invoked. It is set to true by default. Setting this to false got the code working again!

using (var c = new EFContext()) 
{
c
.Configuration.ValidateOnSaveEnabled = false;
Data.User u = new Data.User() { UserId = UserId };
c
.Users.Attach(u);
u
.FailedPasswordAttemptCount = newFailedPasswordAttemptCount;
c
.SaveChanges();
}

Published by

James Gaisford

James is a currently Head of Development for TRW part of the Mubaloo group based in Bristol, UK. James has developed in many languages from Perl via PHP and Java, but has spent the last 10 years focusing on asp.net and javascript. Outside of work James is a failing carpenter.

Leave a Reply

Your email address will not be published. Required fields are marked *