Entity Framework and Concurrency and manually set of timestamp

Concurrency check with Entity Framework is simple, just set concurrency mode property on an entity property to fixed. If you want to use a timestamp column for concurrency check, this blog has a good guide, http://www.undisciplinedbytes.com/2012/03/creating-a-timestamp-column-with-entity-framework/

But when you want to set timestamp manually, if you for example remap your entities to view models. Then you want to set timestamp to the timestamp you have in your view model. But Entity Framework ignores the timestamp you have set and no concurrency exception will be thrown if an update has been since the user started to edit the post.

The solution is to check manually if the timestamp has change. I don’t want to do that every time I writing code to update a post. Because of that I write a partial class of my entity container and overriding SaveChanges(). I also check if the timestamp has been set so we don’t forget to set a timestamp.

 public partial class EntityContainer
    {
        public override int SaveChanges(System.Data.Objects.SaveOptions options)
        {
            var entities = ObjectStateManager.GetObjectStateEntries(EntityState.Modified);
 
            foreach (var entity in entities)
            {
                bool timestampModified = false;
 
                var props = entity.GetModifiedProperties();
                foreach (var prop in props)
                {
                    if (prop.ToLower() == "timestamp")
                    {
                        timestampModified = true;
                        break;
                    }
                } 
 
                    var tsNew = entity.CurrentValues["Timestamp"] as byte[];
                    var tsOrginal = entity.OriginalValues["Timestamp"] as byte[];
 
                    if (tsNew != null && tsOrginal != null)
                    {
                            if (tsNew == tsOrginal && !timestampModified)
                            {
                                throw new Exception("You need to set timestamp when modifing an entity!");
                            }
 
 
                        if (tsNew != tsOrginal)
                        {
                            throw new OptimisticConcurrencyException();
                        } 
                    }
 
 
            }
    }