0

I have a problem when I insert and update data. If a DbUpdateConcurrencyException happens then there are two inserts.

Here is the table

    [Table("Wallet")]
    public partial class Wallet
    {
        public decimal ID { get; set; }

        public decimal Amount { get; set; }

        [Timestamp]
        public byte[] RowVersion { get; set; }

    }

    [Table("Record")]
    public partial class Record
    {
        [Key]
        public int ID { get; set; }

        public string Text { get; set; }

    }    

And here is the action

    using (var ts = _context.Database.BeginTransaction())
    {
        var wallet = _context.Wallets.FirstOrDefault();
        var record = new Record { Text = "XXX" };
        _context.Records.Add(record);

        try
        {
            wallet.Amount += 100;
            await _context.SaveChangesAsync();  // DbUpdateConcurrencyException
        }
        catch (DbUpdateConcurrencyException ex)
        {
            var e = ex.Entries.Single();
            var w = (Wallet)e.Entity;
            _context.Entry(w).Reload();
            w.Amount += 100;
            await _context.SaveChangesAsync();
        }

        ts.Commit();
    }

After the action, there will have two rows of the same record in the table.

How can I avoid this problem?

Dale K
  • 25,246
  • 15
  • 42
  • 71
Byron
  • 1
  • why use Reload and SaveChangesAsync in catch block if you want avoid Concurrency? if do not want avoid cuncurrency use Reload and then SaveChangesAsync without try catch block – Afshin Rashidi Sep 03 '19 at 05:16
  • I want to retry one time for add amount, so I catch the exception and Reload the entity – Byron Sep 03 '19 at 05:34

0 Answers0