Entity Framework: Update single column
Yesterday I blogged about how to delete a detached entity using Entity Framework 5 by only using its Id. A common practice in many applications today is to not actually delete the entity from the database, but instead mark it as deleted and make sure your data access layer filters out those “deleted” items when selecting. So I wanted to implement a general “delete” method that would update the DateDeleted column of an entity without touching any other column. Again I use a detached entity, so the trick is to only mark the DateDeleted column as modified, and not the entire entity. public bool DeleteEntity(T entity) where T : ModelBase { entity.DateDeleted = DateTime.UtcNow; this._databaseContext.Set().Attach(entity); this._databaseContext.Configuration.ValidateOnSaveEnabled = false; this._databaseContext.Entry(entity).Property(m => m.DateDeleted).IsModified = true; int recordsAffected = this._databaseContext.SaveChanges(); this._databaseContext.Configuration.ValidateOnSaveEnabled = true; return recordsAffected == 1; } Notice how I disable validation, and … Continued