【问题标题】:Entity Framework - Updating entity's few columns only实体框架 - 仅更新实体的少数列
【发布时间】:2017-09-21 02:39:34
【问题描述】:

我需要更多地了解实体框架的工作原理。我已经实现了运行正常并完成工作的代码。

但我需要知道这是否是好方法。

我有一个有 8 列的表格,比如说

表1

  • 列 1 (pk)
  • Column2、Column3、Column4、Column5、Column6、Column7、Column8

现在,当我单击按钮时,我需要插入(如果是新的)或更新(对于现有记录)前 6 列。

在同一个按钮点击事件中,作为同一个过程的一部分,我将调用一个存储过程(带有主键 id 的参数,Column1),它将在存储过程本身中获取这 6 个列的值,然后将根据六个列值进行一些计算,并返回我需要在 Column7、Column8 中更新的两个新值。

所以,过程将是:

  • 新记录:插入(六列数据)、计​​算(调用存储过程)、更新(最后两列)

  • 现有记录:更新(六列数据)、计​​算(调用存储过程)、更新(最后两列)

现在,对于插入,我使用

_dbContext.Table1.Add(entity);
 _dbContext.SaveChanges();

对于现有记录更新(前 6 列),我使用

//code - Entity property values are updated with new ones
_dbContext.Table1.Attach(entity);
_dbContext.Entry(entity).State = EntityState.Modified;
_dbContext.SaveChanges();

对于上次更新,Column7,Column8,我使用

var entity = GetById(Id);

if (entity != null)
{
    entity.Column7 = value1;
    _dbContext.Entry(entity).Property(t => t.Column7).IsModified = true;
    entity.Column8 = value2;
    _dbContext.Entry(entity).Property(t => t.Column8).IsModified = true;

    _dbContext.SaveChanges();
}

我不确定为什么我不需要为上次更新附加实体。是不是因为我为上面的同一张表调用了GetById 方法?

不附加实体如何更新列? (如果我附加实体,它会给出错误,说已经被跟踪)

另外,我必须多次调用GetById 来获取两个更新的记录(在现有记录场景中)。还有其他解决方案吗?

【问题讨论】:

    标签: c# entity-framework


    【解决方案1】:

    为此,您可以使用 MapToModel 方法

    这里是例子

    //code - Entity property values are updated with new ones
    var newEntity= new Entity
    {
        Id = p.Id, // the Id you want to update
        Column1= ""  // put value for column/s that you need to update
    };
    newEntity.MapToModel(oldEntity);
    _dbContext.SaveChanges();
    

    【讨论】:

      【解决方案2】:

      恕我直言,如果您通过 Context 获取,我认为您不需要为每个属性指定 IsModified

      除非您更改默认行为,否则 EF 上下文将自动跟踪实体

      EF 知道从数据库加载后哪些实体发生了变化,因此只会更新。

      假设 GetById 正在从数据存储中获取数据。

      var entity = GetById(Id);
      
      if (entity != null)
      {
          entity.Column7 = value1;
          entity.Column8 = value2;
          _dbContext.SaveChanges();
      }
      

      Detect Changes

      Similar Question

      【讨论】:

        猜你喜欢
        • 2012-03-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多