How can I confirm if an async EF6 await db.SaveCha

2019-06-23 22:06发布

My code looks like this:

    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();
    }

I think everything up to the db.SaveChangesAsync is okay but how can I confirm if the db.SaveChangesAsync works before doing a return Ok() ? Ideally I think I should be checking for exceptions and things but I am not sure how I could fit that into this code block.

2条回答
来,给爷笑一个
2楼-- · 2019-06-23 22:41

You can use the following below :)

try {
    int isSaved = await db.SaveChangesAsync();
    if(isSaved > 0){
      // is saved
    }else{
     // is not saved
    }
} catch(e) {
    // handle error here
}
查看更多
霸刀☆藐视天下
3楼-- · 2019-06-23 23:02

From 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.

Check if the result is greater than 0:

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

More info here

Another option is to wrap this with try ... catch block:

try
{
    await db.SaveChangesAsync();
    return Ok();
}
catch (Exception ex)
{
    return NotFound(ex.Message);
}
查看更多
登录 后发表回答