在Entity Framework中更新具有必需属性的实体 [英] Updating an entity with required properties in Entity Framework

查看:149
本文介绍了在Entity Framework中更新具有必需属性的实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我意识到,在没有首先选择它们的情况下,更新实体是一个常见的问题,许多解决方案已经在StackOverflow中,但是在阅读完这些文件后,我仍然遇到问题。

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

但是,这会导致一个 DbEntityValidationException 被抛出,因为我的用户entridy具有一些必需的属性,但这些不一定在更新的实体上设置。

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?

谢谢!

推荐答案

我在这里找到答案:实体框架/ 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();
}

这篇关于在Entity Framework中更新具有必需属性的实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆