ASP.NET MVC + Entity Framework with Concurrency check

后端 未结 3 519
感动是毒
感动是毒 2021-02-06 06:16

I am trying to implement a application following the sample in this page: http://www.asp.net/entity-framework/tutorials/handling-concurrency-with-the-entity-framework-in-an-asp-

3条回答
  •  我在风中等你
    2021-02-06 07:01

    We have overriden the DbContext class, and the SaveChanges method. In it, we look for the TimeStamp values, and if it does not match the value in the OriginalValues collection, we throw an exception.

    we have a BaseEntity type for each entity, and it has a SI_TimeStamp column which is of type TimeStamp.

    public override int SaveChanges()
    {
            foreach (var item in base.ChangeTracker.Entries().Where(r => r.State != System.Data.EntityState.Deleted && 
                                                                                     r.State != System.Data.EntityState.Unchanged))
                if (!item.Entity.SI_TimeStamp.ValueEquals(item.OriginalValues.GetValue("SI_TimeStamp")))
                    throw new Exception("The entity you are trying to update has ben changed since ....!");
    }
    

    you have to place the original value in your forms. Html.HidderFor (r => r.SI_TimeStamp)

    I would actually recommend you to check the timestamp against the original value either when loading or after loading the entity. The overriden DbContext class method is a general solution, and it actually makes sense to check against the timestamp value before trying to save changes back to database.

提交回复
热议问题