Entity Framework Core: Unable to catch SqlException

asp.net-core asp.net-core-signalr c# entity-framework-core

Question

When entering rows into a database table, I'm attempting to incorporate some optimistic locking.

I'm attempting to get a record from the database. A row with the provided key is added first if one does not already exist. I'm trying this right now for high concurrency situations.

The concept is to catch the error and read the object from the database again if the entry has previously been inserted by another thread. I am unable to identify the exception, however.

This is the technique in issue.

    private async Task<Counter> AcquireCounterAsync(string resType)
    {
        var repo = _dbContext.Set<Counter>();

        while (true)
        {
            var ctr = await repo.FindAsync(resType);

            if (ctr != null)
                return ctr;

            ctr = new Counter(resType);

            try
            {
                Console.WriteLine("Trying to add " + resType);
                repo.Add(ctr);
                await _dbContext.SaveChangesAsync();
                Console.WriteLine("Created " + resType);
                return ctr;
            }
            catch (SqlException ex)
            {
                // this block is never entered
                Console.WriteLine("SqlException was thrown: " + ex.Message);
                continue;
            }
        }            
    }

Here is my log; the exception is in German, but it is just the anticipated primary key constraint violation:

Trying to add test/test0
Trying to add test/test0
Created test/test0
fail: Microsoft.EntityFrameworkCore.Database.Command[20102]
      Failed executing DbCommand (157ms) [Parameters=[@p0='?' (Size = 128), @p1='?' (DbType = Int32)], CommandType='Text', CommandTimeout='30']
      SET NOCOUNT ON;
      INSERT INTO [counters] ([ResourceType], [Value])
      VALUES (@p0, @p1);
System.Data.SqlClient.SqlException (0x80131904): Verletzung der PRIMARY KEY-Einschränkung 'PK_counters'. Ein doppelter Schlüssel kann in das dbo.counters-Objekt nicht eingefügt werden. Der doppelte Schlüsselwert ist (test/test0).
Die Anweisung wurde beendet.
   at System.Data.SqlClient.SqlCommand.<>c.<ExecuteDbDataReaderAsync>b__122_0(Task`1 result)
   at System.Threading.Tasks.ContinuationResultTaskFromResultTask`2.InnerInvoke()
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
--- End of stack trace from previous location where exception was thrown ---
   at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot)
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.ExecuteAsync(IRelationalConnection connection, DbCommandMethod executeMethod, IReadOnlyDictionary`2 parameterValues, CancellationToken cancellationToken)
ClientConnectionId:d1f14d55-c95b-4c19-b1bc-468241df225d
Error Number:2627,State:1,Class:14

The questioned class is momentarily inserted into a signal hub. I suspect there may be a fundamental flaw in what I'm doing, but I'm not sure what it is just now.

EDIT: I also attempted to make this procedure synchonous; the outcome was the same; the stack trace from the call at the SignalR hub was only a little bit longer. Thus, it is definitely not captured.

MY FIX: For clarity, I made all methods synchronous AND caught "DbUpdateException" to resolve this. If I use the async methods, I still can't catch "DbUpdateException" or even "Exception." Therefore, this is only marginally connected to this.

1
1
8/27/2018 7:57:40 AM

Popular Answer

ZZZ_tmp
2
8/25/2018 9:22:30 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow