Quantcast
Channel: MySQL Forums - Connector/NET and C#, Mono, .Net
Viewing all articles
Browse latest Browse all 1448

Wrong number of items afftected, No exception thrown when exception is expected (1 reply)

$
0
0
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

Viewing all articles
Browse latest Browse all 1448

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>