Is there any way to implement a transaction in Entity Framework 6 with Web API in Asp.Net?
I am inserting 10 tables separately using Web API calls in a single asp.net web form. Would be helpful if someone would help me in approach or the technical feasibility using Entity framework and Web API.
Thanks
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;
}
Keep in mind:
In Entity Framework, the SaveChanges() method internally creates a transaction and wraps all INSERT, UPDATE and DELETE operations under it. Multiple SaveChanges() calls, create separate transactions, perform CRUD operations and then commit each transaction.
If you really want to perform transaction its really easy:
using (var context = new SomeDbContext())
{
using (DbContextTransaction transaction = context.Database.BeginTransaction()) {
//do stuff
context.SaveChanges();
// multiple saves
context.SaveChanges();
transaction.Commit(); // this is one transaction
}
}