简体   繁体   English

如何使用实体框架更新字段子集?

[英]How to update subset of fields using Entity Framework?

I have multiple objects with subset of fields from the table. 我有多个对象,具有表中字段的子集。 In some cases I should update only one field. 在某些情况下,我应该只更新一个字段。 How to do this properly in Entity Framework 6.0? 如何在Entity Framework 6.0中正确执行此操作? The following code throws error due to database constraints because AddOrUpdate tries to replace all fields but FieldName with empty values. 下面的代码抛出错误是由于数据库约束,因为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;
    }
}

It would be nice to have an extension 有扩展会很好

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

and then use it 然后用它

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

Or maybe Entity Framework already has functionality for this task? 也许实体框架已经具有此任务的功能?

State属性设置为EntityState.Modified

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

Please check if below code works for you: 请检查以下代码是否适合您:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM