Error on updating - System.Data.Entity.Infrastructure.DbUpdateConcurrencyException

Jun 4, 2014 at 9:08 PM
My code behind in web form. I am using ModelBinding :

public partial class frmPaymentDetail : System.Web.UI.Page
{
    private IUnitOfWorkAsync unitOfWorkAsync;
    [Dependency]
    public IUnitOfWorkAsync UnitOfWorkAsync
    {
        get { return unitOfWorkAsync; }
        set { unitOfWorkAsync = value; }
    }

    private IPaymentService paymentService;
    [Dependency]
    public IPaymentService PaymentService
    {
        get { return paymentService; }
        set { paymentService = value; }
    }

    public void UpdatePayment(Payment payment)
    {
        try
        {   
            if (TryUpdateModel(payment))
            {
                paymentService.Update(payment);
                unitOfWorkAsync.SaveChanges();
            }
        }
        catch (Exception ex)
        {
            ModelState.AddModelError("", ex.ToString());
        }
        return;
    }

    public void InsertPayment(Payment payment)
    {
        try
        {
            TryUpdateModel(payment);
            if (ModelState.IsValid)
                paymentService.Insert(payment);
        }
        catch (Exception ex)
        {
            ModelState.AddModelError("", ex.ToString());
        }
        return;
    }

    public Payment GetPayment()
    {
        //testing
        return paymentService.GetPayment(new Guid("b01344f5-0779-4093-b8a5-eeaf41802420"));
    }
}

Unity / Registration :

private static void RegisterDependencies(IUnityContainer container)
    {
        container
            .RegisterType<IDataContextAsync, FESWebContext>(new HierarchicalLifetimeManager())
            .RegisterType<IUnitOfWorkAsync, UnitOfWork>(new HierarchicalLifetimeManager())

            .RegisterType<IPaymentService, PaymentService>()
            .RegisterType<IRepositoryAsync<Payment>, Repository<Payment>>()
}

Update Query from SQL Profiler :
SET [ReferralId] = @0, [ConfirmationNumber] = NULL, [Lastname_Businessname] = @1, [Firstname_Tradename] = @2, [CreatedDate] = @3, [CreatedBy] = @4, [ClientID] = @5,
[ClientReferenceNumber] = @6, [TransactionTypeId] = @7, [TransactionAmount] = @8, [TransactionEffectiveDate] = @9, [AmountTowardPrincipal] = @10, [AmountTowardInterest] = NULL,
[AmountTowardPenalty] = NULL, [AmountTowardCost] = NULL
WHERE (([PaymentId] = @11) AND [Timestamp] IS NULL)
SELECT [Timestamp]
FROM [dbo].[Payments] ..............................


The timestamp is getting a value of 'null' when I try to save on a postback.
Hence, the the UPDATE statement looks like the above.

How can I preserve the timestamp ?
Jun 5, 2014 at 3:41 PM
For now, following is the code that I updated to deal with the concurrency error.

public override int SaveChanges()
    {
        try
        {
            SyncObjectsStatePreCommit();
            var changes = base.SaveChanges();
            SyncObjectsStatePostCommit();
            return changes;
        }
        //TODO Phase 2 : Implement mechanism to let the user know about concurrency issue using appropriate mechanism. 
        catch (DbUpdateConcurrencyException ex) 
        {
            var objContext = ((IObjectContextAdapter)this).ObjectContext;   
            foreach (var dbEntityEntry in ex.Entries)
            {
                dbEntityEntry.OriginalValues.SetValues(dbEntityEntry.GetDatabaseValues());
            }
            return base.SaveChanges();
        }

    }
Jun 19, 2014 at 6:48 PM
Got it to work. See below.

private void SyncObjectsStatePreCommit()
    {
        // update created and modified properties
        foreach (var dbEntityEntry in this.ChangeTracker.Entries())
        {

            dbEntityEntry.State = StateHelper.ConvertState(((IObjectState)dbEntityEntry.Entity).ObjectState);

            switch(dbEntityEntry.State)
            {
                case (EntityState.Added):
                    {
                        ((Entity)dbEntityEntry.Entity).CreatedDatetime = DateTime.Now;
                        ((Entity)dbEntityEntry.Entity).CreatedBy = new Guid("");
                        ((Entity)dbEntityEntry.Entity).ModifiedDatetime = DateTime.Now;
                        ((Entity)dbEntityEntry.Entity).ModifiedBy = new Guid("");                        
                        break;
                    }
                case (EntityState.Modified):
                    {
                        ((Entity)dbEntityEntry.Entity).ModifiedDatetime = DateTime.Now;
                        ((Entity)dbEntityEntry.Entity).ModifiedBy = new Guid("");
                        dbEntityEntry.OriginalValues.SetValues(dbEntityEntry.GetDatabaseValues());

                        break;
                    }
                case (EntityState.Deleted):
                    {
                        break;
                    }
            }
        }
    }
Marked as answer by shaq2676 on 6/19/2014 at 10:48 AM