【问题标题】:How to update subset of fields using Entity Framework?如何使用实体框架更新字段子集?
【发布时间】:2017-03-01 18:59:18
【问题描述】:

我有多个对象,其中包含表中的字段子集。在某些情况下,我应该只更新一个字段。如何在 Entity Framework 6.0 中正确执行此操作?以下代码由于数据库限制而引发错误,因为AddOrUpdate 尝试将除FieldName 之外的所有字段替换为空值。

public static TheField Set(TheField f)
{
    using (var dbContext = new MyModel())
    {
            dbContext.MyEntity.AddOrUpdate(new MyEntity()
            {
                ForeignId = f.ForeignId,
                FieldName = f.FieldName,
            });
            dbContext.SaveChanges();

            return f;
    }
}

如果有扩展名就好了

public static class MyExtension
{
    public static void AddOrUpdateSchema<TEntity, TKey>(this IDbSet<TEntity> set, TKey id, string schema, 
        params TEntity[] entities) where TEntity : class
    {
        // ...
    }
}

然后使用它

public class MyEntity
{
    [Key]
    public int ForeignId { get; set; }

    [UpdateSchema("Schema")]
    public string FieldName { get; set; }
    // ...
}

public class MyEntityView
{
    public int ForeignId { get; set; }
    public string FieldName { get; set; }

    public static MyEntityView Set(MyEntityView f)
    {
        using (var dbContext = new MyModel())
        {
            dbContext.MyEntity.AddOrUpdateSchema(f.ForeignId, "Schema", new MyEntity()
            {
                FieldName = f.FieldName,
            });
            dbContext.SaveChanges();

            return f;
        }
    }
}

或者也许 Entity Framework 已经有这个任务的功能?

【问题讨论】:

  • 您是指仅更新单个(或多个但不是全部)属性(属性)吗?如果是这样,这就是我正在使用的: public virtual void UpdateProperty(int id, Expression> navigationProperty, object propertyValue) { var entityToUpdate = this.dbSet.Find(id); var entry = this.context.Entry(entityToUpdate); entry.Property(navigationProperty).CurrentValue = propertyValue; entry.State = EntityState.Modified; this.context.SaveChanges(); }
  • 是的,在大多数情况下,我需要更新表的一个字段或预定义的属性子集。

标签: c# entity-framework-6 insert-update upsert


【解决方案1】:

请检查以下代码是否适合您:

using (var dbContext = new MyModel())
{   
    if (dbContext.MyEntities.Any(e => e.ForeignId == f.ForeignId))
    {
        dbContext.MyEntities.Attach(f);
        dbContext.ObjectStateManager.ChangeObjectState(f, EntityState.Modified);
    }
    else
    {
        dbContext.MyEntities.AddObject(f);
    }

    dbContext.SaveChanges();
}

【讨论】:

    【解决方案2】:

    State 属性设置为EntityState.Modified

    db.Entry(entity).State = EntityState.Modified;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-08
      • 1970-01-01
      相关资源
      最近更新 更多