如何确认异步 EF6 await db.SaveChangesAsync() 是否按预期工作?

How can I confirm if an async EF6 await db.SaveChangesAsync() worked as expected?

我的代码如下所示:

    public async Task<IHttpActionResult> Delete(int id)
    {
        var userId = Int32.Parse(User.Identity.GetUserId());   
        UserTest userTest = await db.UserTests.FindAsync(id);
        if (userTest == null)
        {
            return NotFound();
        }
        if (userTest.UserId != userId)
        {
            return Unauthorized();
        }
        db.UserTests.Remove(userTest);
        await db.SaveChangesAsync();
        return Ok();
    }

我认为 db.SaveChangesAsync 之前的一切都没有问题,但是我如何在执行 return Ok() 之前确认 db.SaveChangesAsync 是否有效?理想情况下,我认为我应该检查异常和其他事情,但我不确定如何将其放入此代码块中。

来自 msdn:

public virtual Task<int> SaveChangesAsync()

Return Value Type: System.Threading.Tasks.Task A task that represents the asynchronous save operation. The task result contains the number of objects written to the underlying database.

检查结果是否大于0:

if(await db.SaveChangesAsync() > 0)
{
     .....
}

More info here

另一种选择是用 try ... catch 块包装它:

try
{
    await db.SaveChangesAsync();
    return Ok();
}
catch (Exception ex)
{
    return NotFound(ex.Message);
}

您可以使用以下内容:)

try {
    int writtenEntriesCount = await db.SaveChangesAsync();
    if(writtenEntriesCount > 0){
      // is saved
    }else{
     // is not saved
    }
} catch(e) {
    // handle error here
}

如果有帮助,我通常会使用它:

try
        {
            _context.Events.Add(entity);

            await _context.SaveChangesAsync(cancellationToken);
            return new CommandResult() { IsSuccess = true };
        }
        catch (Exception ex)
        {
            return new CommandResult() { IsSuccess = false,IsError =True, Message=ex.Message };
        }



public class CommandResult
{
    public bool IsSuccess { get; internal set; }
    public bool IsError { get; internal set; }
    public string Message { get; internal set; }
}