确保调用api成功并保存自己的成功

确保调用api成功并保存自己的成功

本文介绍了确保调用api成功并保存自己的成功的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,当我将ASP.NET MVC与EF结合使用并从其他网站(也使用Entity Framework)
调用Web API时,问题出在

Hello I found problem when I use ASP.NET MVC with EF and call Web API from other website(that have also use Entity Framework)the problem is that

我想确保MVC SaveChanges()和Web API SaveChanges()都成功。

I want to make sure that both MVC SaveChanges() and Web API SaveChanges() succeed both together.

这是我梦dream以求的伪代码

Here's my dream pseudo code

public ActionResult Operation()
{
    Code Insert Update Delete....

    bool testMvcSaveSuccess = db.TempSaveChanges();  //it does not have this command.

    if(testMvcSaveSuccess == true)
    {
       bool isApiSuccess = CallApi(); //insert data to Other Web App


       if(isApiSuccess == true)
       {
          db.SaveChanges(); //Real Save
       }
    }
}

从上面代码,如果它没有 db.TempSaveChanges(),则Web API可能会成功,但是MVC SaveChanges()可能会失败。

From above code, if it doesn't have db.TempSaveChanges(), maybe Web API will be successful, but MVC SaveChanges() might fail.

推荐答案

所以没有像 TempSaveChanges 这样的东西,因为还有更好的东西:

So there is nothing like TempSaveChanges because there is something even better: Transactions.

交易是一个IDisposable(可以在using块中使用),并且具有 Commit Rollback 之类的方法。 。

Transaction is an IDisposable (can be used in a using block) and has methods like Commit and Rollback.

小例子:

private void TestTransaction()
{
    var context = new MyContext(connectionString);

    using (var transaction = context.Database.BeginTransaction())
    {
        // do CRUD stuff here

        // here is your 'TempSaveChanges' execution
        int changesCount = context.SaveChanges();

        if (changesCount > 0)
        // changes were made
        {
            // this will do the real db changes
            transaction.Commit();
        }
        else
        {
            // no changes detected -> so do nothing
            // could use 'transaction.Rollback();' since there are no changes, this should not be necessary
            // using block will dispose transaction and with it all changes as well
        }
    }
}

我已从GitHub中提取了此示例存储库。随意使用星/克隆/叉...

I have extracted this example from my GitHub Exercise.EntityFramework repository. Feel free to Star/Clone/Fork...

这篇关于确保调用api成功并保存自己的成功的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 10:17