Wrong number of items afftected, No exception thrown when exception is expected
Posted by: Giorgi Dalakishvili
Date: September 11, 2023 03:27AM

When there is no row in the database that is affected by an update statement, SaveChanges still returns 1 and doesn't throw DbUpdateConcurrencyException.

Here is sample code

var optionsBuilder = new DbContextOptionsBuilder<DemoContext>();
optionsBuilder.UseMySQL("Server=127.0.0.1;Port=3306;Database=EFExc;User Id=demo;Password=secret;")
.LogTo(s => Debug.WriteLine(s)).EnableSensitiveDataLogging();

var context = new DemoContext(optionsBuilder.Options);
context.Database.EnsureCreated();

var product = new Product { Name = "Test Product" };
context.Products.Add(product);

var changeCount = context.SaveChanges();
Console.WriteLine($"Inserted {changeCount} rows");

changeCount = context.Database.ExecuteSqlRaw($"Delete from products where id={product.Id}");
Console.WriteLine($"Deleted {changeCount} rows");

var count = context.Products.Count();
Console.WriteLine($"Items in database: {count}");

product.Name = "G";
changeCount = context.SaveChanges();
Console.WriteLine($"Updated {changeCount} rows");


The row that is being updated is deleted by ExecuteSqlRaw call but context.SaveChanges() still returns 1 and doesn't throw DbUpdateConcurrencyException.

This is the output I get when running the app:

Inserted 1 rows
Deleted 1 rows
Items in database: 0
Updated 1 rows

Options: ReplyQuote


Subject
Written By
Posted
Wrong number of items afftected, No exception thrown when exception is expected
September 11, 2023 03:27AM


Sorry, only registered users may post in this forum.

Content reproduced on this site is the property of the respective copyright holders. It is not reviewed in advance by Oracle and does not necessarily represent the opinion of Oracle or any other party.