Esempio n. 1
0
 public long AddUser(VoUser user)
 {
     //Demonstration of creating an AmbientDbContext in transaction mode
     using (var dbContextScope = new DbContextScopeFactory().CreateAmbientDbContextInReadonlyMode <BloggerDbContext>())
     {
         var addedUser = _userOperations.AddUser(user);
         dbContextScope.SaveChanges();
         dbContextScope.Commit();
         return(addedUser.UserId);
     }
 }
        public void AddBlog(VoBlog voBlog)
        {
            //Demonstration of creating an AmbientDbContext in transaction mode
            using (var dbContextScope = new DbContextScopeFactory().CreateAmbientDbContextInTransactionMode <BloggerDbContext>())
            {
                bool exceptionOccured = false;
                var  user             = _userOperations.GetUser(voBlog.UserId);
                try
                {
                    Console.WriteLine("BlogPostCreationFailureCount :" + user.BlogPostCreationFailureCount);
                    var blog = _blogOperations.AddBlog(voBlog);
                    var post = _postOperations.AddPost(voBlog.Post);
                    blog.BlogPost = post;
                    dbContextScope.SaveChanges();
                    dbContextScope.Commit();
                }
                catch (Exception)
                {
                    exceptionOccured = true;
                    throw;
                }
                finally
                {
                    if (exceptionOccured)
                    {
                        var userOperations = new UserOperations();
                        using (
                            var nonAmbientdbContextScope =
                                new DbContextScopeFactory().CreateNonAmbientDbContextInTransactionMode <BloggerDbContext>())
                        {
                            //Setting the user operations dbContext with the dbContext from DbContextScope just created
                            //else we would be using ambient DbContext.
                            userOperations.UpdateBlogCreationFailureCount(voBlog.UserId);

                            var updateduser = userOperations.GetUser(voBlog.UserId);
                            nonAmbientdbContextScope.RefreshParentCacheWithUpdatedEntities(new List <User> {
                                updateduser
                            });
                            Console.WriteLine("BlogPostCreationFailureCount :" + user.BlogPostCreationFailureCount);
                        }
                    }
                }
            }
        }