Using Transactions or SaveChanges(false) and AcceptAllChanges()?

后端 未结 3 1507
[愿得一人]
[愿得一人] 2020-11-22 06:15

I have been investigating transactions and it appears that they take care of themselves in EF as long as I pass false to SaveChanges() and then cal

3条回答
  •  时光取名叫无心
    2020-11-22 06:58

    If you are using EF6 (Entity Framework 6+), this has changed for database calls to SQL.
    See: http://msdn.microsoft.com/en-us/data/dn456843.aspx

    use context.Database.BeginTransaction.

    From MSDN:

    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(); //Required according to MSDN article 
                throw; //Not in MSDN article, but recommended so the exception still bubbles up
            } 
        } 
    } 
    

提交回复
热议问题