Reputation: 614
I have a Job table and I'll use the newly inserted Job.Id to insert another table called CompanyJobs
To insert a job I do
var job = new Job{Name = "Name"}
dbContext.Jobs.Add(job);
dbContext.SaveChanges();
Then with the newly inserted Job I use it's ID to insert CompanyJobs
var companyJobs = new CompanyJob{Name="Name",JobId = Job.Id};
dbContext.CompanyJobs.Add(companyJobs);
dbContext.SaveChanges();
Let's say there is a possibility of error in inserting CompanyJobs
How can I enclose the 2 dbContext.SaveChanges() in one transaction?
Upvotes: 0
Views: 83
Reputation: 7216
Another options is to use TransactionScope:
using (var transactionScope = new TransactionScope())
{
var job = new Job{Name = "Name"}
dbContext.Jobs.Add(job);
dbContext.SaveChanges();
var category = dbContext.Categories.Find(2);
job.Categories.Add(category);
dbContext.SaveChanges();
transactionScope.Complete();
}
If Complete
has not been called when exiting the using
block (ie: an exception has occurred), the transaction is rolled back.
If you're using async methods, you need to pass the TransactionScopeAsyncFlowOption.Enabled
parameter to the Transactionscope's constructor.
Upvotes: 1
Reputation: 16825
First, you do not need two SaveChanges
, you can do both in one call:
var category = dbContext.Categories.Find(2);
var job = new Job{Name = "Name"}
job.Categories.Add(category);
dbContext.Jobs.Add(job);
dbContext.SaveChanges();
If you really need two transactions, then according to this docs you should:
using (var dbContextTransaction = dbContext.Database.BeginTransaction())
{
try
{
var job = new Job{Name = "Name"}
dbContext.Jobs.Add(job);
dbContext.SaveChanges();
var category = dbContext.Categories.Find(2);
job.Categories.Add(category);
dbContext.SaveChanges();
dbContextTransaction.Commit();
}
catch (Exception)
{
dbContextTransaction.Rollback();
}
}
Upvotes: 0