locked
Trigger exception how to roll back RRS feed

  • Question

  • Hi,

         I am using entity framework 6.0. I am adding a entity from code logic based on that back sql will fire some triggers. The triggers have some exception. So I need to roll back the transaction. But the connection become null. Could not able to rollback. please suggest how to roll back when trigger have exception.

    Thanks

    Monday, February 27, 2017 2:49 AM

All replies

  • Hi Deepthi Kiran,

    You could use DbContextTransaction to rollback the transaction when throw the exception. like this:

    using (var context = new BloggingContext()) 
                { 
                    using (var dbContextTransaction = context.Database.BeginTransaction()) 
                    { 
                        try 
                        { 
                            context.Database.ExecuteSqlCommand( 
                                @"UPDATE Blogs SET Rating = 5" + 
                                    " WHERE Name LIKE '%Entity Framework%'" 
                                ); 
     
                            var query = context.Posts.Where(p => p.Blog.Rating >= 5); 
                            foreach (var post in query) 
                            { 
                                post.Title += "[Cool Blog]"; 
                            } 
     
                            context.SaveChanges(); 
     
                            dbContextTransaction.Commit(); 
                        } 
                        catch (Exception) 
                        { 
                            dbContextTransaction.Rollback(); 
                        } 
                    } 
                } 
    

    For more information, please refer to:

    https://msdn.microsoft.com/en-us/library/dn456843(v=vs.113).aspx

    Best regards,

    Cole Wu


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Tuesday, February 28, 2017 6:05 AM