【发布时间】: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