DbContext.SaveChangesAsync异常处理 [英] DbContext.SaveChangesAsync Exception Handling

查看:142
本文介绍了DbContext.SaveChangesAsync异常处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Visual Studio 2013中使用异步操作和Entity Framework支持搭建新的 ApiController 时,某些方法会包装解决方案

Web API脚手架控制器遵循REST语义,因此PUT实际上是记录的更新.

MSDN消息指出,如果未更新记录,则会引发异常,因此在这种情况下,如果记录无法更新,它将引发异常.如果该记录不存在,则返回404 not found.

总而言之,尽管数据库引发了异常,但是在REST服务的上下文中,这可能是有效的情况(因为记录不存在,所以未执行任何更新),并且不是真正的错误.其他异常将冒泡给客户端.

When scaffolding a new ApiController with asynchronous actions and Entity Framework support in Visual Studio 2013, some methods wrap DbContext.SaveChangesAsync calls in try-catch blocks.

For instance, the Put method,

try
{
    await db.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
    if (!EmployeeExists(id))
    {
        return NotFound();
    }
    throw;
}

From msdn.microsoft.com about DbUpdateConcurrencyException,

Exception thrown by DbContext when it was expected that SaveChanges for an entity would result in a database update but in fact no rows in the database were affected.

The DbUpdateConcurrencyException is derived from DbUpdateException and there are a handful of other exceptions that can be thrown from the DbContext.SaveChangesAsync method.

I'm wondering why there are no catch clauses for these other exceptions? Is it for the sake of brevity? Or do they simply not belong at this level in the application?

解决方案

The Web API scaffolding controller follows REST semantics, so a PUT is effectively an update of a record.

The MSDN message states that the exception is thrown if a record was not updated so in this case it will throw an exception if the record failed to be updated. If the record did not exist, a 404 not found is returned.

In summary, although an exception is thrown by the database, it may be a valid case in the context of a REST service (no update performed because the record did not exist) and not a real error. The other exceptions will be bubbled up to the client.

这篇关于DbContext.SaveChangesAsync异常处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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