Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...