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();
}
This worked fine in EF4. However 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 and telling EF which properties have been modified,
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.
This question states that Attach will only work for entities derived from EntityObject. So I assume EF5 objects do not derive from this.
Anyone know how I can update my entity without having to specify the all non-nullable string fields each time.
Feels like I am missing something really obvious….
If this is an existing user, you could just do this…
By the way, as an aside, in EF5 code first, entity classes don’t derive from anything, but can still be attached.
Or, you go back to your way of attaching, but I think you need to turn off validation for this save, as it seems EF only validates the whole entity or nothing