✅ do i use BeginTransaction() correctly?
hi, am i using BeginTransaction() correctly? here is my code:
so after the offer has been checked it can still be deleted afterwards. By using BeginTransaction() i can have every condition (that is inside the transaction using block) atomic, if something changes, for example my offer gets deleted, SaveChangesAsync throws an exception and calls the Rollback function. right?
using (var context = dbContextFactory.CreateDbContext())
{
using (var transaction = context.Database.BeginTransaction())
{
try
{
var offer = await context.Offers.Where(x => x.OfferId == tableEntity.Offer.OfferId).FirstOrDefaultAsync();
if (offer is not null)
{
tableEntity.PendingOffer.Id = Guid.NewGuid().ToString();
tableEntity.PendingOffer.OfferId = tableEntity.Offer.OfferId;
tableEntity.PendingOffer.BuyerId = User.Id;
tableEntity.PendingOffer.SellerId = ProfileUser.Id;
context.PendingOffers.Add(tableEntity.PendingOffer);
await context.SaveChangesAsync();
StateHasChanged();
transaction.Commit();
}
else
{
tableEntitiesHandler.OfferTableEntities.Remove(tableEntity);
}
}
catch
{
transaction.Rollback();
}
}
}using (var context = dbContextFactory.CreateDbContext())
{
using (var transaction = context.Database.BeginTransaction())
{
try
{
var offer = await context.Offers.Where(x => x.OfferId == tableEntity.Offer.OfferId).FirstOrDefaultAsync();
if (offer is not null)
{
tableEntity.PendingOffer.Id = Guid.NewGuid().ToString();
tableEntity.PendingOffer.OfferId = tableEntity.Offer.OfferId;
tableEntity.PendingOffer.BuyerId = User.Id;
tableEntity.PendingOffer.SellerId = ProfileUser.Id;
context.PendingOffers.Add(tableEntity.PendingOffer);
await context.SaveChangesAsync();
StateHasChanged();
transaction.Commit();
}
else
{
tableEntitiesHandler.OfferTableEntities.Remove(tableEntity);
}
}
catch
{
transaction.Rollback();
}
}
}so after the offer has been checked it can still be deleted afterwards. By using BeginTransaction() i can have every condition (that is inside the transaction using block) atomic, if something changes, for example my offer gets deleted, SaveChangesAsync throws an exception and calls the Rollback function. right?
