Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
141 views
in Technique[技术] by (71.8m points)

c# - Make sure that call api success and save myself success

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

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

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

Small example:

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...