【问题标题】:Is that possible, DbContext.SaveChanges() returns 0 but doesn't have an exception?这可能吗, DbContext.SaveChanges() 返回 0 但没有异常?
【发布时间】:2012-06-21 06:55:50
【问题描述】:

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

【问题讨论】:

  • 您需要添加更多信息,否则没人能提供帮助。你能发布你的代码吗?

标签: c# asp.net entity-framework c#-4.0 entity-framework-4


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

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

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

    【讨论】:

      【解决方案3】:

      我的回答没有提到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
          }
      }
      

      【讨论】:

        【解决方案4】:

        根据the documentationDbContext.SaveChanges的返回值为

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

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

        【讨论】:

        • 没错 - 例如:如果您删除不再存在的行,您将获得 0 个受影响的行
        • @CarstenKönig 不,如果您删除不再存在的行,数据库将返回“0 行受影响”,EF 会将其转换为异常。 “无需保存实体”表示在调用 SaveChanges 之前上下文中没有任何更改。
        • 真的吗?必须尝试一下,但我认为我过去也遇到过类似的问题,但没有例外,但感谢您的更正
        • 如果它返回-1?
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-10-09
        • 2014-02-07
        相关资源
        最近更新 更多