这可能,DbContext.SaveChanges()返回0但没有异常?

cag*_*gin 20 c# asp.net entity-framework entity-framework-4 c#-4.0

我使用Entity Framework 4.0.是否有可能SaveChanges()返回0但不会抛出异常?例如,添加后.

这是我的代码:

try
{
    _context.CodeProducts.Add(entity);
    _context.SaveChanges();

    //Shell I control return result from SaveChanges() in here.
    //However doesn't throw an exceoption?

    return new MethodResponse()
    {
        ResultText = "Successful",
        Type = MethodResponse.ResponseType.Succeed
    };
}
catch (OptimisticConcurrencyException exc)
{
    throw exc;
}
catch (UpdateException exc)
{
    throw exc;
}
catch (Exception exc)
{
    throw exc;
}
Run Code Online (Sandbox Code Playgroud)

Kla*_*sen 29

根据文档,返回值DbContext.SaveChanges

写入底层数据库的对象数.

所以只有在没有实体需要保存到数据库时才能看到.


小智 5

用于删除和保存的实体框架db.SaveChanges()返回受影响的行数。然而,在使用 Fakes Framework(存根和垫片)的测试中,返回的值将始终为 0。

如果调用过程中出现错误,则会抛出异常。这意味着任何依赖于db.SaveChanges()确认返回的大于零的值的调用方法都无法测试相同的值。

db.SaveChanges()当方法使用返回值来评估给定操作中受影响的行数时,这可能至关重要。