22

我使用实体框架 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;
}
4

4 回答 4

33

根据文档DbContext.SaveChanges,返回值为

写入基础数据库的对象数。

因此,只有在不需要将实体保存到数据库中时,您才能看到。

于 2012-06-19T08:53:32.367 回答
4

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

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

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

于 2014-06-30T18:10:00.507 回答
0

我的回答没有提到DbContext,但如果有人在使用XEntities并遇到同样的问题,您可以尝试:

using (var entities = new XEntities())
{
    var product = entities.Products.SingleOrDefault(x => x.Id == id);
    product.Type = "New type"; // modifying

    int flag = entities.SaveChanges(); // 1
    // or await entities.SaveChangesAsync(); // 1
}

问题:

public class Demo
{
    private XEntities _entities = new XEntities();

    public void Test(int id)
    {
        var product = _entities.Product.SingleOrDefault(x => x.Id == id);
        product.Type = "New type"; // modifying

        int flag = _entities.SaveChanges(); // 0 <<<====
        // or await entities.SaveChangesAsync(); // 0  <<<====

        // you need to create new instance of XEntities to apply changes
    }
}
于 2016-12-23T04:56:58.740 回答
0

请注意,如果您更新实体并且实际上没有对其进行任何更改,SaveChangesAsync()它将返回0并且Exception将是null.

于 2020-09-30T12:26:36.150 回答