Pop
Pop

Reputation: 525

How to perform rollback in Entity Framework 5?

How to perform rollback in Entity Framework 5, .Net Framework 4?

Do I have to call db.SaveChanges(); under //commit or is db.usp_UpdateRoleUser suffice?

What code should be under //rollback?

public static bool UpdateRoleUser(int component_type, string oldRole, string oldUser, string oldAuth_value, string newRole, string newUser, string newAuth_value)
{
    using (var db = new VMIEntities())
    {
        int recordAffected = db.usp_UpdateRoleUser(newRole, newUser, newAuth_value, oldRole, oldUser, oldAuth_value, component_type);

        if (recordAffected == 1)
        {
            //commit
            return true;
        }
        else
        {
            //rollback
            return false;
        }
    }
}

Upvotes: 1

Views: 396

Answers (1)

Ahmed Oumezzine
Ahmed Oumezzine

Reputation: 151

I do the same search on the internet and find this answer I think you'll help you , I make a copy of this link : stackoverflow.com/a/1070134/585968

public static bool UpdateRoleUser(int component_type, string oldRole, string oldUser, string oldAuth_value, string newRole, string newUser, string newAuth_value)
{
    bool saved = false;
    using (var transaction = new System.Transactions.TransactionScope())
    {
        try
        {
            var db = new VMIEntities();
            db.usp_UpdateRoleUser(newRole, newUser, newAuth_value, oldRole, oldUser, oldAuth_value, component_type);

            context.SaveChanges();
            saved = true;
        }
        catch(OptimisticConcurrencyException e)
        {
            //Handle the exception
            context.SaveChanges();
        }
        finally
        {
            if(saved)
            {
                transaction.Complete();
                context.AcceptAllChanges();
            }
        }
    }
}

Upvotes: 1

Related Questions