Please note: This blog is no longer active. My new blog is located at http://blog.timwheeler.io

Sunday, March 9, 2014

TimeStamps with Entity Framework

So I've been building an MVC 5, EF6 solution with Code First Migrations.
Got what I think is a great structure of abstraction thanks to Le Long's Post.

One thing that wasn't obvious (to me at least), was how to handle concurrency with EF and the Scaffolded Views.
When editing an object, the TimeStamp was never returned, and of course EF would throw a "DbUpdateConcurrencyException".

Here is a solution that worked for me:

  1. Create a base entity class with a TimeStamp on it
  2. Add the attributes: [Timestamp, ScaffoldColumn(false)]
  3. Edit the MVC View and add a hidden field for the timestamp


Base Class and Attributes
I defined a base class for all entities requiring concurrency.
public abstract class PersistedEntity : EntityBase
{
        [Timestamp, ScaffoldColumn(false)]
        public byte[] TimeStamp { get; set; }
}

MVC View
I found that the view did not by itself return the TimeStamp with the model when posting data back to the server.  So I added this after the @Html.BeginForm():
@Html.HiddenFor(model => model.TimeStamp)

It was then returned back to the server, and the entity could be saved correctly.





1 comment:

  1. The Best New Online Casino Sites for 2021
    The Best New Online Casino Sites for 2021 · luckyclub.live Slots Empire – Best New Online Casino Site in USA · Bovada – Best New Online Casino Online for UK Players · Red Dog –

    ReplyDelete