更新实体与实体框架要求的性能 [英] Updating an entity with required properties in Entity Framework

查看:123
本文介绍了更新实体与实体框架要求的性能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认识到,更新实体没有首先选择它们是一个普遍的问题,很多解决方案已经在计算器上,阅读这些我仍然有一个问题,但是之后

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.

我用下面的代码更新用户entitiy:使用

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 被抛出,因为我的用户entitiy有一定要求的特性,但这些不一定在实体更新设置。

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:暂时禁用验证

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

这篇关于更新实体与实体框架要求的性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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