Updating an object with the required properties in the Entity Framework

I understand that updating objects without first selecting them is a common problem, and many solutions are already in StackOverflow, however after reading these problems I still have a problem.

I use the following code to update User entitiy:

using (var context = GetContext()) { var userEntity = new UserEntity() { ID = userUpdate.ID }; context.Users.Attach(userEntity); context.Entry(userEntity).CurrentValues.SetValues(userUpdate); context.SaveChanges(); } 

However, this leads to the fact that a DbEntityValidationException thrown due to the fact that my User entitiy has some required properties, but they are not necessarily set in the updated object.

Is there a way around this or is it just a case of removing the required properties?

Thanks!

+5
source share
2 answers

I found the answer here: Entity Framework / MVC3: temporarily disable validation

By temporarily disabling validation, I can bypass the validation and insert any number of values โ€‹โ€‹without first obtaining the necessary properties:

 using (var context = GetContext()) { var userEntity = new UserEntity() { ID = userUpdate.ID }; context.Users.Attach(userEntity); context.Entry(userEntity).CurrentValues.SetValues(userUpdate); // Disable entity validation context.Configuration.ValidateOnSaveEnabled = false; context.SaveChanges(); } 
+4
source

If you only want to update certain fields in your entity without first extracting the whole thing from the database:

 var userEntity = new UserEntity() { ID = userUpdate.ID }; userEntity.SomeProperty = userUpdate.SomeProperty; //Tell EF to only update the SomeProperty value: context.Entry(userEntity).Property(x => x.SomeProperty).IsModified = true; context.SaveChanges(); 
+1
source

All Articles