Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating an entity with required properties in Entity Framework

I realise that updating entities without first selecting them is a common problem and many solutions are already on StackOverflow, however after reading these I'm still having a problem.

I'm using the following code to update a 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 results in a DbEntityValidationException being thrown because my User entitiy has some required properties but these aren't necessarily set on the updated entity.

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

Thanks!

like image 964
Alfie Woodland Avatar asked Oct 13 '15 16:10

Alfie Woodland


1 Answers

I've found an answer here: Entity Framework/MVC3: temporarily disable validation

By temporarily disabling validation I can bypass the checks and insert any number of values without retrieving the required properties first:

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();
}
like image 164
Alfie Woodland Avatar answered Oct 13 '22 19:10

Alfie Woodland