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? The following code throws error due to database constraints because AddOrUpdate
tries to replace all fields but FieldName
with empty values.
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();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.