私は、テーブルのフィールドのサブセットを持つ複数のオブジェクトを持っています。場合によっては、フィールドを1つだけ更新する必要があります。 Entity Framework 6.0で正しくこれを行うには? AddOrUpdate
は空の値でFieldName
以外のすべてのフィールドを置換しようとするため、次のコードはデータベースの制約によりエラーをスローします。Entity Frameworkを使用してフィールドのサブセットを更新するにはどうすればよいですか?
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(); } –
Nathan
はい、ほとんどの場合、テーブルの1つのフィールドまたは定義済みのプロパティのサブセットを更新する必要があります。 – amuliar