I'm using Entity Framework 5.0 with DbContext and POCO entities. There's a simple entity containing 3 properties:
public class Record
{
public int Id { get; set; }
public string Title { get; set; }
public bool IsActive { get; set; }
}
The Title field is always unmodified, and the UI simply displays it without providing any input box to modify it. That's why the Title
field is set to null
when the form is sent to the server.
Here's how I tell EF to perform partial update of the entity (IsActive
field only):
public class EFRepository<TEntity>
{
...
public void PartialUpdate(TEntity entity, params Expression<Func<TEntity, object>>[] propsToUpdate)
{
dbSet.Attach(entity);
var entry = _dbContext.Entry(entity);
foreach(var prop in propsToUpdate)
contextEntry.Property(prop).IsModified = true;
}
}
and the call:
repository.PartialUpdate(updatedRecord, r => r.IsActive);
Calling SaveChanges
method, I get the DbEntityValidationException
, that tells me, Title
is required. When I set dbContext.Configuration.ValidateOnSaveEnabled = false
, everything is OK.
Is there any way to avoid disabling validation on the whole context and to tell EF not to validate properties that are not being updated?
Thanks in advance.
var person = new Person { Id = 5 }; dbSet.Attach(person); dbSet.Entry(person).Property(p => p.IsDeleted).IsModified = true; dbContext.SaveChanges();
will cause the same exception. Does DbContext validation work well with stub entities at all? I'd like to aviod retrieving the whole entity from database just for marking it as deleted. – WoodcockdbSet.Attach(entity); dbContext.Entry(entity).State = EntityState.Modified; dbContext.SaveChanges();
will update the whole entity. If you tell EF explicitly, what properties to update, only these properties are updated.dbSet.Attach(entity); dbContext.Entry(entity).Property(e => e.Title).IsModified = true; dbContext.SaveChanges();
will update Title only. With disabled validation, this works well. – Woodcock(entity.IsActive = false)
, but so far I do not mark it as updated(e => e.IsActive).IsModified = true;
it will not be updated.entity.State = EntityState.Modified
marks the whole entity as updated at once. – WoodcockdbSet.SqlCommand("UPDATE entity SET deleted = true where x = y")
, this is MUCH simpler than the path you are taking. – Noonberg