Below is the sample code snippet would give a clarity on the multiple tables Create or Update transaction. The first table column ID is the foreign key for other child tables. So if there is an exception on child table insertion, the parent table record will also get rolled back. And thus the whole table which is included in transaction will get rolled back successfully.
public bool CreateOrUpdateEmployee(Common common)
{
bool IstransactionComplete= false;
EmployeeEntities DbContext = new EmployeeEntities();
using (var transaction = DbContext.Database.BeginTransaction())
{
try
{
if (common.Mode == Modes.CREATE) //Modes - User defined Enum
{
DbContext = CreateFinanceEmployees(common, DbContext); //DbContext.savechanges() inside this method.
DbContext = CreateManufacturingEmployee(common, DbContext); //DbContext.savechanges() inside this method.
DbContext = CreateLogisticsEmployee(common, DbContext); //DbContext.savechanges() inside this method.
}
else
{
DbContext = UpdateFinanceEmployees(common, DbContext); //DbContext.savechanges() inside this method.
DbContext = UpdateManufacturingEmployee(common, DbContext); //DbContext.savechanges() inside this method.
DbContext = UpdateLogisticsEmployee(common, DbContext); //DbContext.savechanges() inside this method.
}
**transaction.Commit();**
IstransactionComplete=true;
}
catch (Exception ex)
{
**transaction.Rollback();**
IstransactionComplete=false;
}
finally
{
transaction.Dispose();
}
}
return IstransactionComplete;
}