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

标签 c# entity-framework

我意识到在不先选择实体的情况下更新实体是一个常见问题,StackOverflow 上已经有许多解决方案,但是在阅读这些内容后我仍然遇到问题。

我正在使用以下代码来更新用户实体:

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

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

有什么办法解决这个问题,还是只是删除所需属性的情况?

谢谢!

最佳答案

我在这里找到了答案:Entity Framework/MVC3: temporarily disable validation

通过暂时禁用验证,我可以绕过检查并插入任意数量的值,而无需首先检索所需的属性:

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

关于c# - 在 Entity Framework 中更新具有所需属性的实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33107859/

相关文章:

c# - PowerShell 排序顺序不正确

c# - 在 EWS 中访问房间日历返回 "No mailbox with such guid"

c# - 强制接口(interface)的子类实现 ToString

c# - 如何指定配置类型的名称?

entity-framework - System.Drawing.Image EntityType 'Image' 没有定义键。定义此 EntityType 的键

c# - MySQL 相当于 SQLite SQLiteConnection Context

database - 在 Entity Framework 中使用累积的存储桶值

c# - 影响 EF 代码中的外键列命名(CTP5)

c# - 如何在 Web API 中实现 HttpMessageHandler?

c# - 将委托(delegate)用法从 C# 转换为 VB