C
C#14mo ago
İrşat

❔ transaction.Rollback(); vs SaveChanges; at the end

using (var transaction = _db.Database.BeginTransaction())
{
try
{
// Remove all existing testimonials
_db.Testimonials.RemoveRange(_db.Testimonials);

// Add new testimonials
_db.Testimonials.AddRange(newTestimonials);

await _db.SaveChangesAsync();

// If everything is successful, commit the transaction
transaction.Commit();

return Ok(new { message = "Success" });
}
catch (Exception)
{
// If an exception occurs, roll back the transaction
transaction.Rollback();
return StatusCode(500, new { message = "Error" });
}
}
using (var transaction = _db.Database.BeginTransaction())
{
try
{
// Remove all existing testimonials
_db.Testimonials.RemoveRange(_db.Testimonials);

// Add new testimonials
_db.Testimonials.AddRange(newTestimonials);

await _db.SaveChangesAsync();

// If everything is successful, commit the transaction
transaction.Commit();

return Ok(new { message = "Success" });
}
catch (Exception)
{
// If an exception occurs, roll back the transaction
transaction.Rollback();
return StatusCode(500, new { message = "Error" });
}
}
Would the records be safe in case AddRange fails if I don't use RollBack?
3 Replies
Omnissiah
Omnissiah14mo ago
ef would use transactions by default, as i understand it
JakenVeina
JakenVeina14mo ago
if you only have a single .SaveChanges() call, then the entire transaction is really redundant unless you're using a non-default isolation level, for the transaction EF will execute all the underlying queries within a transaction, if not already inside a transaction context
Accord
Accord14mo ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server