I have an entity that I know already exists in the database but which is not currently being tracked by the context. I force the context to track the entity using the Attach method on DbSet. Then set 'IsModified' = true
for necessary properties. But EF
tries to update every property in db table and SaveChanges()
method throws exception that some properties is required and can't be empty. Though I mark only one property as modified.
I'm using EF v.6.0.
Here is my code:
public bool ChangeState(int id, bool state)
{
try
{
var obj = new T {ID = id, Hidden = state};
_context.Set<T>().Attach(obj);
_context.Entry(obj).Property(x => x.Hidden).IsModified = true;
return _context.SaveChanges() == 1;
}
catch (DbEntityValidationException dbEx)
{
...
}
}
}
Have you any idea?