简体   繁体   English

如何在 Asp.Net 中使用 Web Api 在 Entity Framework 6 中实现事务?

[英]How to implement transaction in Entity Framework 6 with Web Api in Asp.Net?

Is there any way to implement a transaction in Entity Framework 6 with Web API in Asp.Net?有没有办法在 Entity Framework 6 中使用 Asp.Net 中的 Web API 实现事务?

I am inserting 10 tables separately using Web API calls in a single asp.net web form.我在单个 asp.net Web 表单中使用 Web API 调用分别插入 10 个表。 I am seeking ideas or technical feasibility suggestions using Entity framework and Web API.我正在使用实体框架和 Web API 寻求想法或技术可行性建议。

Keep in mind:记住:

In Entity Framework, the SaveChanges() method internally creates a transaction and wraps all INSERT, UPDATE and DELETE operations under it.在实体框架中,SaveChanges() 方法在内部创建一个事务并将所有 INSERT、UPDATE 和 DELETE 操作包装在其下。 Multiple SaveChanges() calls, create separate transactions, perform CRUD operations and then commit each transaction.多次 SaveChanges() 调用,创建单独的事务,执行 CRUD 操作,然后提交每个事务。

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
 }
}

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.第一个表列 ID 是其他子表的外键。 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;
    }

Yes.是的。

You can use the context provided by EF to create a transaction scope.您可以使用 EF 提供的上下文来创建事务范围。 At the end of the scope you can commit or rollback.在范围的末尾,您可以提交或回滚。

You can do something like that:你可以这样做:

class WebController
{
    public Response restMethod()
    {
        var context = getYourDBCOntext();
        using(var dbContextTransaction = context.Database.BeginTransaction())
        {
            try {
                // do something with the DB
                context.Database.ExecuteSqlCommand( /* sql command */ );

                // save changes
                context.SaveChanges();
                // commit transaction
                dbContextTransaction.Commit();
            catch(Exception)
            {
                // Rollback in case of an error
                dbContextTransaction.Rollback();
            }
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM