【问题标题】:Best way to update a record using Entity Framework使用实体框架更新记录的最佳方式
【发布时间】:2018-04-30 15:11:23
【问题描述】:

我想使用实体框架更新我的表。但是,我得到一个错误。

我的EfRepositoryBase 类正在实现IEntityRepository。这种方法有什么问题?

public bool UpdateWithProperty(TEntity entity, params Expression<Func<TEntity, object>>[] properties)
{
    using (var context = new TContext())
    {
        context.Set<TEntity>().Attach(entity);

        var updatedEntity = context.Entry(entity);

        foreach (var property in properties)
        {
           updatedEntity.Property(property).IsModified = true;
        }

        updatedEntity.State = EntityState.Modified;
        context.SaveChanges();
    }

    return true;
}

错误:

无法将值 NULL 插入到列“用户名”、表“Nextt.dbo.Users”中;列不允许空值。更新失败。

【问题讨论】:

  • 这可能没什么问题。您正在尝试将字段设置为空白。我猜想传入的实体的UserName 属性是空白的。这在数据库中是不允许的。您需要检查在运行时传递的数据并确认这一点。您的应用程序应该具有不允许此为空的逻辑
  • 异常是不言自明的:EF 尝试使用空值更新“UserName”字段,而 DB 中的列设置为“NOT NULL”。您需要检查传递的可能包含 null 值的数据并对其进行检查 null (例如,使用 if 块)。

标签: c# asp.net asp.net-mvc entity-framework


【解决方案1】:

你可以这样使用。

    db.context.Attach(obj);
    DbEntityEntry entry = db.Entry(obj);
    foreach (var proprty in entry.OriginalValues.PropertyNames)
    {
        if(entry.CurrentValues.GetValue<object>(proprty) != null)
            if (!object.Equals(entry.GetDatabaseValues().GetValue<object>(proprty), entry.CurrentValues.GetValue<object>(proprty)))
            {
                entry.Property(proprty).IsModified = true;
            }
    }

   db.SaveChanges();

【讨论】:

  • 这是一种不同的方法。
  • 是的,这很明显。现在它有什么帮助?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-21
  • 2018-04-19
  • 1970-01-01
  • 2015-05-10
  • 1970-01-01
  • 2018-12-16
相关资源
最近更新 更多