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 then enable it after saving the changes. This is because I don’t want to load the entity before changing DateDeleted. I want to use only the Id, so I want to avoid having to fulfill all validation rules on an entity.

All my model classes derive from the ModelBase class, which looks like this:

public abstract class ModelBase { public ModelBase() { this.DateCreated = DateTime.UtcNow; } public DateTime DateCreated { get; set; } public DateTime? DateModifed { get; set; } public DateTime? DateDeleted { get; set; } }

To “delete” an entity, I can instantiate an entity, give it an Id, and call the delete method:

Account account = new Account { Id = 123 }; DeleteEntity(account);