简体   繁体   English

在Entity Framework中更新具有所需属性的实体

[英]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. 我意识到更新实体而不首先选择它们是一个常见的问题,并且许多解决方案已经在StackOverflow上,但是在阅读之后我仍然遇到问题。

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. 但是,这会导致抛出DbEntityValidationException ,因为我的用户权限具有一些必需的属性,但这些属性不一定在更新的实体上设置。

Is there any way around this or is it simply a case of removing the required properties? 有没有办法解决这个问题,还是仅仅是删除所需属性的情况?

Thanks! 谢谢!

I've found an answer here: Entity Framework/MVC3: temporarily disable validation 我在这里找到了答案: 实体框架/ MVC3:暂时禁用验证

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();
}

If you only want to update particular fields in your entity without having to retrieve the entire thing from the database first: 如果您只想更新实体中的特定字段而不必首先从数据库中检索整个事物:

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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM