我怎样才能确认是否异步EF6等待db.SaveChangesAsync()和预期一样? [英] How can I confirm if an async EF6 await db.SaveChangesAsync() worked as expected?

查看:2606
本文介绍了我怎样才能确认是否异步EF6等待db.SaveChangesAsync()和预期一样?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的code是这样的:

 公共异步任务< IHttpActionResult>删除(INT ID)
    {
        变种用户id = Int32.Parse(User.Identity.GetUserId());
        UserTest userTest =等待db.UserTests.FindAsync(ID);
        如果(userTest == NULL)
        {
            返回NOTFOUND();
        }
        如果(userTest.UserId!=用户id)
        {
            返回未授权();
        }
        db.UserTests.Remove(userTest);
        等待db.SaveChangesAsync();
        返回OK();
    }

我觉得一切到db.SaveChangesAsync是好的,但我怎么能确认是否db.SaveChangesAsync做一个好的回报()之前的作品?理想情况下,我认为我应该检查异常和事情,但我不知道我怎么能它放到这个code座。


解决方案

从MSDN:

  public虚拟任务< INT> SaveChangesAsync()


  

返回值类型:System.Threading.Tasks.Task一项任务
  再presents异步保存操作。任务结果包含
  写入到底层数据库的对象的数量。


检查结果大于0:

 如果(等待db.SaveChangesAsync()0)
{
     .....
}

更多信息这里

另一种方法是用来包装这个的try ... catch 块:

 尝试
{
    等待db.SaveChangesAsync();
    返回OK();
}
赶上(异常前)
{
    返回NOTFOUND(ex.Message);
}

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.

解决方案

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

这篇关于我怎样才能确认是否异步EF6等待db.SaveChangesAsync()和预期一样?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆