Is that possible, DbContext.SaveChanges() returns 0 but doesn't have an exception? Is that possible, DbContext.SaveChanges() returns 0 but doesn't have an exception? asp.net asp.net

Is that possible, DbContext.SaveChanges() returns 0 but doesn't have an exception?


According to the documentation, the return value of DbContext.SaveChanges is

The number of objects written to the underlying database.

So what you see is only possible, when no entities needed to be saved to the database.


Entity Framework's db.SaveChanges() for deletes and saves returns the number rows being affected. In test using the Fakes Framework (stubs and shims), however, the value returned will always be 0.

If there is an error in the call, then an exception will be thrown. The implication is that any calling method relying on a value greater than zero returned from db.SaveChanges() for confirmation cannot be tested for that same value.

This may prove critical when a method is using the db.SaveChanges() return value to evaluate the number of rows affected in a given operation.


My answer is not mentioning about DbContext, but if someone is using XEntities and getting same problem, you can try:

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}

The problem:

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