SqlServer_Database_can_be_created_with_columns_that_implicitly_total_more_that_8060_bytes_and_data_longer_than_8060_can_be_inserted
            ()
        {
            EnsureDatabaseInitialized(() => new ModelWithWideProperties());

            ExtendedSqlAzureExecutionStrategy.ExecuteNew(
                () =>
            {
                using (new TransactionScope())
                {
                    using (var context = new ModelWithWideProperties())
                    {
                        var entity = new EntityWithImplicitWideProperties
                        {
                            Property1 = new String('1', 1000),
                            Property2 = new String('2', 1000),
                            Property3 = new String('3', 1000),
                            Property4 = new String('4', 1000),
                        };

                        context.ImplicitlyWide.Add(entity);

                        context.SaveChanges();

                        entity.Property1 = new String('A', 4000);
                        entity.Property2 = new String('B', 4000);

                        context.SaveChanges();
                    }
                }
            });
        }
        public void Scenario_Relate_using_FK()
        {
            EnsureDatabaseInitialized(() => new SimpleModelContext());

            ExtendedSqlAzureExecutionStrategy.ExecuteNew(
                () =>
            {
                using (new TransactionScope())
                {
                    using (var context = new SimpleModelContext())
                    {
                        var product = new Product
                        {
                            Name       = "Bovril",
                            CategoryId = "Foods"
                        };
                        context.Products.Add(product);
                        context.SaveChanges();

                        // Scenario ends; simple validation of final state follows
                        Assert.NotNull(product);
                        Assert.Equal(EntityState.Unchanged, GetStateEntry(context, product).State);
                        Assert.Equal("Foods", product.CategoryId);
                    }
                }
            });
        }
Example #3
0
        public void Verify_insert_update_delete_for_guid_identity_column()
        {
            ExtendedSqlAzureExecutionStrategy.ExecuteNew(
                () =>
            {
                using (new TransactionScope())
                {
                    using (var context = new GuidIdentityColumnContext())
                    {
                        var customer   = context.Customers.Single();
                        var orders     = customer.Orders.ToList();
                        orders[0].Name = "Changed Name";
                        context.Orders.Remove(orders[1]);
                        context.SaveChanges();
                    }

                    using (var context = new GuidIdentityColumnContext())
                    {
                        var customer = context.Customers.Single();
                        var orders   = customer.Orders;

                        Assert.Equal(1, orders.Count());
                        Assert.Equal("Changed Name", orders.Single().Name);
                    }
                }
            });
        }
        private static void InsertAndUpdateWithDecimals(
            decimal insertValue, decimal insertExpected, decimal updateValue, decimal updateExpected)
        {
            ExtendedSqlAzureExecutionStrategy.ExecuteNew(
                () =>
            {
                using (new TransactionScope())
                {
                    using (var context = new ArubaContext())
                    {
                        // Insert
                        var allTypes = context.AllTypes.Add(CreateArubaAllTypes(insertValue));
                        context.SaveChanges();

                        ValidateSavedValues(context, allTypes, insertExpected);

                        // Update
                        UpdateArubaAllTypes(allTypes, updateValue);
                        context.SaveChanges();

                        ValidateSavedValues(context, allTypes, updateExpected);
                    }
                }
            });
        }
Example #5
0
        public void Modifying_non_generated_key_throws()
        {
            ExtendedSqlAzureExecutionStrategy.ExecuteNew(
                () =>
            {
                using (new TransactionScope())
                {
                    using (var context = new GearsOfWarContext())
                    {
                        var squad = new Squad
                        {
                            Id   = 10,
                            Name = "Lima",
                        };

                        context.Squads.Add(squad);
                        context.SaveChanges();
                        squad.Id = 20;

                        Assert.Throws <InvalidOperationException>(() => context.SaveChanges())
                        .ValidateMessage(typeof(DbContext).Assembly(), "ObjectStateEntry_CannotModifyKeyProperty", null, "Id");
                    }
                }
            });
        }
        public void Generic_DbEntityEntry_State_calls_DetectChanges_for_detached_unchanged_entities()
        {
            ExtendedSqlAzureExecutionStrategy.ExecuteNew(
                () =>
            {
                using (var context = new SimpleModelContext())
                {
                    using (new TransactionScope())
                    {
                        var entry = context.Entry(new Product());
                        context.Products.Add(entry.Entity);
                        context.SaveChanges();

                        // Ensure that the entity doesn't have a change tracking proxy
                        Assert.Equal(
                            entry.Entity.GetType(),
                            ObjectContext.GetObjectType(entry.Entity.GetType()));

                        // DetectChanges is called the first time the state is queried for a detached entity
                        Assert.Equal(EntityState.Unchanged, entry.State);

                        entry.Entity.Name = "foo";

                        Assert.Equal(EntityState.Unchanged, entry.State);
                    }
                }
            });
        }
Example #7
0
        public void Fixup_of_two_relationships_that_share_a_key_results_in_correct_removal_of_dangling_foreign_keys()
        {
            ExtendedSqlAzureExecutionStrategy.ExecuteNew(
                () =>
            {
                using (var context = new Context2172())
                {
                    context.Database.Initialize(force: false);
                }

                using (new TransactionScope())
                {
                    using (var context = new Context2172())
                    {
                        var user = context.Users.Add(new User2172 {
                            Id = 1
                        });
                        context.SaveChanges();

                        var message =
                            context.Messages.Add(new Message2172 {
                            Id = 1, CreatedById = 1, ModifiedById = 1
                        });
                        context.SaveChanges();

                        context.Messages.Remove(message);
                        context.SaveChanges();

                        context.Entry(user).State = EntityState.Detached;

                        Assert.NotNull(context.Users.First(u => u.Id == user.Id));
                    }
                }
            });
        }
Example #8
0
        public void Modifying_identity_non_key_throws()
        {
            ExtendedSqlAzureExecutionStrategy.ExecuteNew(
                () =>
            {
                using (new TransactionScope())
                {
                    using (var context = new GearsOfWarContext())
                    {
                        var squad = new Squad
                        {
                            Id   = 10,
                            Name = "Lima",
                        };

                        context.Squads.Add(squad);
                        context.SaveChanges();
                        var squadInternalNumber = squad.InternalNumber;
                        squad.InternalNumber    = squadInternalNumber + 1;

                        Assert.Throws <DbUpdateException>(() => context.SaveChanges())
                        .InnerException.InnerException.ValidateMessage(
                            typeof(DbContext).Assembly(),
                            "Update_ModifyingIdentityColumn",
                            null,
                            "Identity",
                            "InternalNumber",
                            "CodeFirstDatabaseSchema.Squad");
                    }
                }
            });
        }
Example #9
0
        public void Verify_that_deletes_precede_inserts()
        {
            ExtendedSqlAzureExecutionStrategy.ExecuteNew(
                () =>
            {
                using (new TransactionScope())
                {
                    using (var context = new GearsOfWarContext())
                    {
                        var squad1 = new Squad
                        {
                            Id   = 3,
                            Name = "Alpha",
                        };

                        context.Squads.Add(squad1);
                        context.SaveChanges();

                        var squad2 = new Squad
                        {
                            Id   = 3,
                            Name = "Bravo",
                        };

                        context.Squads.Add(squad2);
                        context.Squads.Remove(squad1);
                        context.SaveChanges();

                        Assert.Equal(
                            "Bravo", context.Squads.Where(o => o.Id == 3).Select(s => s.Name).Single());
                    }
                }
            });
        }
Example #10
0
        public void Modifying_identity_generated_key_throws()
        {
            ExtendedSqlAzureExecutionStrategy.ExecuteNew(
                () =>
            {
                using (new TransactionScope())
                {
                    using (var context = new GearsOfWarContext())
                    {
                        var tag = new CogTag
                        {
                            Id   = Guid.NewGuid(),
                            Note = "Some Note",
                        };

                        context.Tags.Add(tag);
                        context.SaveChanges();
                        tag.Id = Guid.NewGuid();

                        Assert.Throws <InvalidOperationException>(() => context.SaveChanges())
                        .ValidateMessage(typeof(DbContext).Assembly(), "ObjectStateEntry_CannotModifyKeyProperty", null, "Id");
                    }
                }
            });
        }
Example #11
0
        public void Read_and_write_using_AdvancedPatternsModelFirst_created_from_T4_template()
        {
            var building18 = CreateBuilding();

            ExtendedSqlAzureExecutionStrategy.ExecuteNew(
                () =>
            {
                using (new TransactionScope())
                {
                    using (var context = new AdvancedPatternsModelFirstContext())
                    {
                        context.Buildings.Add(building18);

                        var foundBuilding = context.Buildings.Find(new Guid(Building18Id));
                        Assert.Equal("Building 18", foundBuilding.Name);

                        context.SaveChanges();
                    }

                    using (var context = new AdvancedPatternsModelFirstContext())
                    {
                        var foundBuilding = context.Buildings.Find(new Guid(Building18Id));
                        Assert.Equal("Building 18", foundBuilding.Name);
                        Assert.Equal(3, context.Entry(foundBuilding).Collection(b => b.Offices).Query().Count());

                        var arthursOffice = context.Offices.Single(o => o.Number == "1/1125");
                        Assert.Same(foundBuilding, arthursOffice.GetBuilding());
                    }
                }
            });
        }
Example #12
0
        public void Update_resulting_in_data_truncation_throws_exception()
        {
            ExtendedSqlAzureExecutionStrategy.ExecuteNew(
                () =>
            {
                using (new TransactionScope())
                {
                    using (var context = new GearsOfWarContext())
                    {
                        var cogTagNoteMaxLength = 40;
                        var cogTag = new CogTag
                        {
                            Id   = Guid.NewGuid(),
                            Note = new string('A', cogTagNoteMaxLength),
                        };

                        context.Tags.Add(cogTag);
                        context.SaveChanges();

                        cogTag.Note = new string('A', cogTagNoteMaxLength + 1);
                        Assert.Throws <DbUpdateException>(() => context.SaveChanges());
                    }
                }
            });
        }
Example #13
0
        public void Read_and_write_using_MonsterModel_created_from_T4_template()
        {
            int orderId;
            int?customerId;

            ExtendedSqlAzureExecutionStrategy.ExecuteNew(
                () =>
            {
                using (new TransactionScope())
                {
                    using (var context = new MonsterModel())
                    {
                        var entry   = context.Entry(CreateOrder());
                        entry.State = EntityState.Added;

                        context.SaveChanges();

                        orderId    = entry.Entity.OrderId;
                        customerId = entry.Entity.CustomerId;
                    }

                    using (var context = new MonsterModel())
                    {
                        var order = context.Order.Include(o => o.Customer).Single(o => o.CustomerId == customerId);

                        Assert.Equal(orderId, order.OrderId);
                        Assert.True(order.Customer.Orders.Contains(order));
                    }
                }
            });
        }
Example #14
0
        public void Delete_GearsOfWar_entities_using_stored_procedures()
        {
            ExtendedSqlAzureExecutionStrategy.ExecuteNew(
                () =>
            {
                using (new TransactionScope())
                {
                    using (var context = new GearsOfWarStoredProceduresContext())
                    {
                        var cities  = context.Cities.ToList();
                        var gears   = context.Gears.ToList();
                        var squads  = context.Squads.ToList();
                        var tags    = context.Tags.ToList();
                        var weapons = context.Weapons.ToList();

                        context.Cities.RemoveRange(cities);
                        context.Gears.RemoveRange(gears);
                        context.Squads.RemoveRange(squads);
                        context.Tags.RemoveRange(tags);
                        context.Weapons.RemoveRange(weapons);
                        context.SaveChanges();
                    }

                    using (var context = new GearsOfWarStoredProceduresContext())
                    {
                        Assert.Equal(0, context.Cities.Count());
                        Assert.Equal(0, context.Gears.Count());
                        Assert.Equal(0, context.Squads.Count());
                        Assert.Equal(0, context.Tags.Count());
                        Assert.Equal(0, context.Weapons.Count());
                    }
                }
            });
        }
Example #15
0
        public void Update_Many_to_Many_relationship_using_stored_procedures()
        {
            ExtendedSqlAzureExecutionStrategy.ExecuteNew(
                () =>
            {
                using (new TransactionScope())
                {
                    List <int?> usedWeaponIds;
                    List <int?> unusedWeaponIds;
                    using (var context = new GearsOfWarStoredProceduresContext())
                    {
                        var gear      = context.Gears.OrderBy(g => g.Nickname).ThenBy(g => g.Squad).First();
                        usedWeaponIds = gear.Weapons.Select(w => w.Id).ToList();

                        var unusedWeapons = context.Weapons
                                            .Where(w => !usedWeaponIds.Contains(w.Id)).ToList();

                        unusedWeaponIds = unusedWeapons.Select(w => w.Id).ToList();
                        gear.Weapons    = unusedWeapons;
                        context.SaveChanges();
                    }

                    using (var context = new GearsOfWarStoredProceduresContext())
                    {
                        var gear = context.Gears.OrderBy(g => g.Nickname).ThenBy(g => g.Squad).First();
                        Assert.True(gear.Weapons.All(w => unusedWeaponIds.Contains(w.Id)));
                    }
                }
            });
        }
Example #16
0
 /// <summary>
 /// Drops the database that would be used for the context. Usually used to avoid errors during initialization.
 /// </summary>
 /// <param name="createContext"> A func to create the context. </param>
 protected static void DropDatabase(Func <DbContext> createContext)
 {
     using (var context = createContext())
     {
         ExtendedSqlAzureExecutionStrategy.ExecuteNew(
             () => context.Database.Delete());
     }
 }
Example #17
0
 /// <summary>
 /// Ensures the database for the context is created and seeded.  This is typically used
 /// when a test is going to use a transaction to ensure that the DDL happens outside of
 /// the transaction.
 /// </summary>
 /// <param name="createContext"> A func to create the context. </param>
 protected static void EnsureDatabaseInitialized(Func <DbContext> createContext)
 {
     using (var context = createContext())
     {
         ExtendedSqlAzureExecutionStrategy.ExecuteNew(
             () => context.Database.Initialize(force: false));
     }
 }
Example #18
0
        public void Cascade_delete_works_properly_on_one_to_many_relationship()
        {
            ExtendedSqlAzureExecutionStrategy.ExecuteNew(
                () =>
            {
                using (new TransactionScope())
                {
                    using (var context = new GearsOfWarContext())
                    {
                        var gearsBefore = context.Gears.Count();
                        var gear1       = new Gear
                        {
                            FullName = "Gear1",
                            Nickname = "Gear1",
                            Tag      = new CogTag
                            {
                                Id   = Guid.NewGuid(),
                                Note = "Tag1",
                            },
                        };

                        var gear2 = new Gear
                        {
                            FullName = "Gear2",
                            Nickname = "Gear2",
                            Tag      = new CogTag
                            {
                                Id   = Guid.NewGuid(),
                                Note = "Tag2",
                            },
                        };

                        var squad = new Squad
                        {
                            Name    = "Charlie",
                            Members = new List <Gear> {
                                gear1, gear2
                            },
                        };

                        context.Squads.Add(squad);
                        context.SaveChanges();

                        var gearsAfterAdd = context.Gears.Count();

                        context.Squads.Remove(squad);
                        context.SaveChanges();

                        var gearsAfterRemove = context.Gears.Count();

                        Assert.Equal(gearsBefore, gearsAfterRemove);
                        Assert.Equal(gearsBefore + 2, gearsAfterAdd);
                    }
                }
            });
        }
Example #19
0
        public void CommitFailureHandler_supports_nested_transactions()
        {
            MutableResolver.AddResolver <Func <TransactionHandler> >(
                new TransactionHandlerResolver(() => new CommitFailureHandler(), null, null));

            try
            {
                using (var context = new BlogContextCommit())
                {
                    ExtendedSqlAzureExecutionStrategy.ExecuteNew(
                        () =>
                    {
                        context.Database.Delete();
                        Assert.Equal(1, context.Blogs.Count());
                    });

                    context.Blogs.Add(new BlogContext.Blog());

                    ExtendedSqlAzureExecutionStrategy.ExecuteNew(
                        () =>
                    {
                        using (var transaction = context.Database.BeginTransaction())
                        {
                            using (var innerContext = new BlogContextCommit())
                            {
                                using (var innerTransaction = innerContext.Database.BeginTransaction())
                                {
                                    Assert.Equal(1, innerContext.Blogs.Count());
                                    innerContext.Blogs.Add(new BlogContext.Blog());
                                    innerContext.SaveChanges();
                                    innerTransaction.Commit();
                                }
                            }

                            context.SaveChanges();
                            transaction.Commit();
                        }
                    });
                }

                ExtendedSqlAzureExecutionStrategy.ExecuteNew(
                    () =>
                {
                    using (var context = new BlogContextCommit())
                    {
                        Assert.Equal(3, context.Blogs.Count());
                    }
                });
            }
            finally
            {
                MutableResolver.ClearResolvers();
            }

            DbDispatchersHelpers.AssertNoInterceptors();
        }
Example #20
0
        public void Scenario_Using_two_databases()
        {
            EnsureDatabaseInitialized(() => new LoginsContext());
            EnsureDatabaseInitialized(() => new SimpleModelContext());

            ExtendedSqlAzureExecutionStrategy.ExecuteNew(
                () =>
            {
                using (new TransactionScope())
                {
                    using (var context = new LoginsContext())
                    {
                        var login = new Login
                        {
                            Id       = Guid.NewGuid(),
                            Username = "******"
                        };
                        context.Logins.Add(login);
                        context.SaveChanges();

                        // Scenario ends; simple validation of final state follows
                        Assert.Same(login, context.Logins.Find(login.Id));
                        Assert.Equal(EntityState.Unchanged, GetStateEntry(context, login).State);
                    }
                }
            });

            ExtendedSqlAzureExecutionStrategy.ExecuteNew(
                () =>
            {
                using (new TransactionScope())
                {
                    using (var context = new SimpleModelContext())
                    {
                        var category = new Category
                        {
                            Id = "Books"
                        };
                        var product = new Product
                        {
                            Name     = "The Unbearable Lightness of Being",
                            Category = category
                        };
                        context.Products.Add(product);
                        context.SaveChanges();

                        // Scenario ends; simple validation of final state follows
                        Assert.Equal(EntityState.Unchanged, GetStateEntry(context, product).State);
                        Assert.Equal(EntityState.Unchanged, GetStateEntry(context, category).State);
                        Assert.Equal("Books", product.CategoryId);
                        Assert.Same(category, product.Category);
                        Assert.True(category.Products.Contains(product));
                    }
                }
            });
        }
Example #21
0
        public static void DoStuff(BlogContext context)
        {
            Blog blog = null;
            Post post = null;

            ExtendedSqlAzureExecutionStrategy.ExecuteNew(
                () =>
            {
                blog = context.Blogs.Single();
                Assert.Equal("Half a Unicorn", blog.Title);

                post = blog.Posts.Single();
                Assert.Equal("Wrap it up...", post.Title);
            });

            blog.Posts.Add(
                new Post
            {
                Title = "Throw it away..."
            });

            ExtendedSqlAzureExecutionStrategy.ExecuteNew(
                () =>
            {
                using (context.Database.BeginTransaction())
                {
                    Assert.Equal(1, context.SaveChanges());
                    Assert.Equal(
                        new[] { "Throw it away...", "Wrap it up..." },
                        context.Posts.AsNoTracking().Select(p => p.Title).OrderBy(t => t));
                }
            });

#if !NET40
            ExtendedSqlAzureExecutionStrategy.ExecuteNew(
                () =>
            {
                using (context.Database.BeginTransaction())
                {
                    post.Title = "I'm a logger and I'm okay...";

                    var saveTask = context.SaveChangesAsync();
                    saveTask.Wait();
                    Assert.Equal(1, saveTask.Result);

                    var queryTask = context.Posts
                                    .AsNoTracking()
                                    .Select(p => p.Title).OrderBy(t => t)
                                    .ToListAsync();
                    queryTask.Wait();

                    Assert.Equal(new[] { "I'm a logger and I'm okay..." }, queryTask.Result);
                }
            });
#endif
        }
Example #22
0
 public void No_TransactionHandler_and_no_ExecutionStrategy_throws_CommitFailedException_on_false_commit_fail()
 {
     Execute_commit_failure_test(
         c => Assert.Throws <DataException>(() => ExtendedSqlAzureExecutionStrategy.ExecuteNew(c)).InnerException.ValidateMessage("CommitFailed"),
         c => Assert.Throws <CommitFailedException>(() => ExtendedSqlAzureExecutionStrategy.ExecuteNew(c)).ValidateMessage("CommitFailed"),
         expectedBlogs: 2,
         useTransactionHandler: false,
         useExecutionStrategy: false,
         rollbackOnFail: false);
 }
        public void DetectChanges_can_be_called_twice_for_nullable_composite_key_with_related_entities()
        {
            ExtendedSqlAzureExecutionStrategy.ExecuteNew(
                () =>
            {
                using (var context = new BlogContext663())
                {
                    context.Configuration.AutoDetectChangesEnabled = false;
                    context.Database.Initialize(force: false);

                    using (context.Database.BeginTransaction())
                    {
                        var blog1 = context.CompositeBlogs.Add(new CompositeBlog663());
                        var blog2 = context.CompositeBlogs.Add(new CompositeBlog663());

                        blog1.Posts = new List <CompositePost663> {
                            new CompositePost663()
                        };
                        blog2.Posts = new List <CompositePost663> {
                            new CompositePost663()
                        };

                        context.ChangeTracker.DetectChanges();
                        context.ChangeTracker.DetectChanges();

                        Assert.Equal(EntityState.Added, context.Entry(blog1).State);
                        Assert.Equal(EntityState.Added, context.Entry(blog2).State);
                        Assert.Equal(EntityState.Added, context.Entry(blog1.Posts.First()).State);
                        Assert.Equal(EntityState.Added, context.Entry(blog2.Posts.First()).State);

                        blog1.Id1 = 1;
                        blog1.Id2 = 2;
                        blog2.Id1 = 1;
                        blog2.Id2 = 3;

                        context.ChangeTracker.DetectChanges();
                        context.SaveChanges();

                        Assert.Equal(EntityState.Unchanged, context.Entry(blog1).State);
                        Assert.Equal(EntityState.Unchanged, context.Entry(blog2).State);
                        Assert.Equal(EntityState.Unchanged, context.Entry(blog1.Posts.First()).State);
                        Assert.Equal(EntityState.Unchanged, context.Entry(blog2.Posts.First()).State);

                        Assert.NotNull(blog1.Id1);
                        Assert.NotNull(blog1.Id2);
                        Assert.NotNull(blog2.Id1);
                        Assert.NotNull(blog2.Id2);
                        Assert.Equal(blog1.Id1, blog1.Posts.First().BlogId1);
                        Assert.Equal(blog1.Id2, blog1.Posts.First().BlogId2);
                        Assert.Equal(blog2.Id1, blog2.Posts.First().BlogId1);
                        Assert.Equal(blog2.Id2, blog2.Posts.First().BlogId2);
                    }
                }
            });
        }
Example #24
0
        public void Command_trees_for_initialization_and_simple_query_and_update_commands_can_be_logged()
        {
            // Make sure that HistoryContext has been used to ensure test runs consistently regardless of
            // whether or not other tests have run before it.
            using (var initContext = new BlogContextNoInit())
            {
                ExtendedSqlAzureExecutionStrategy.ExecuteNew(
                    () =>
                {
                    initContext.Database.Initialize(force: false);
                });
            }

            var logger = new CommandTreeLogger();

            DbInterception.Add(logger);

            BlogContextLogAll context;

            try
            {
                using (context = new BlogContextLogAll())
                {
                    BlogContext.DoStuff(context);
                }
            }
            finally
            {
                DbInterception.Remove(logger);
            }

            // Sanity check that we got tree creations logged
            Assert.True(logger.Log.OfType <DbQueryCommandTree>().Any(t => t.DataSpace == DataSpace.CSpace));
            Assert.True(logger.Log.OfType <DbQueryCommandTree>().Any(t => t.DataSpace == DataSpace.SSpace));
            Assert.True(logger.Log.OfType <DbInsertCommandTree>().Any(t => t.DataSpace == DataSpace.SSpace));
#if !NET40
            Assert.True(logger.Log.OfType <DbUpdateCommandTree>().Any(t => t.DataSpace == DataSpace.SSpace));

            Assert.True(
                logger.Log.OfType <DbUpdateCommandTree>()
                .Any(
                    t => t.SetClauses.OfType <DbSetClause>()
                    .Any(
                        c => ((DbPropertyExpression)c.Property).Property.Name == "Title" &&
                        (string)((DbConstantExpression)c.Value).Value == "I'm a logger and I'm okay...")));
#endif

            foreach (var interceptionContext in logger.LogWithContext.Select(t => t.Item2))
            {
                Assert.Contains(context, interceptionContext.DbContexts);
            }
        }
Example #25
0
        public void Update_GearsOfWar_entities_using_stored_procedures()
        {
            ExtendedSqlAzureExecutionStrategy.ExecuteNew(
                () =>
            {
                using (new TransactionScope())
                {
                    using (var context = new GearsOfWarStoredProceduresContext())
                    {
                        var city = context.Cities.OrderBy(c => c.Name).First();
#if NET452
                        city.Location = DbGeography.FromText("POINT(12 23)", DbGeography.DefaultCoordinateSystemId);
#endif
                        context.SaveChanges();

                        var tag  = context.Tags.OrderBy(t => t.Id).First();
                        tag.Note = "Modified Note";
                        context.SaveChanges();

                        var gear  = context.Gears.OrderBy(g => g.Nickname).ThenBy(g => g.SquadId).First();
                        gear.Rank = MilitaryRank.General;
                        context.SaveChanges();

                        var squad  = context.Squads.OrderBy(s => s.Id).First();
                        squad.Name = "Modified Name";
                        context.SaveChanges();

                        var weapon  = context.Weapons.OrderBy(w => w.Id).First();
                        weapon.Name = "Modified Name";
                        context.SaveChanges();
                    }

                    using (var context = new GearsOfWarStoredProceduresContext())
                    {
                        var city   = context.Cities.OrderBy(c => c.Name).First();
                        var tag    = context.Tags.OrderBy(t => t.Id).First();
                        var gear   = context.Gears.OrderBy(g => g.Nickname).ThenBy(g => g.SquadId).First();
                        var squad  = context.Squads.OrderBy(s => s.Id).First();
                        var weapon = context.Weapons.OrderBy(w => w.Id).First();

#if NET452
                        Assert.Equal(12, city.Location.Longitude);
                        Assert.Equal(23, city.Location.Latitude);
#endif
                        Assert.Equal("Modified Note", tag.Note);
                        Assert.Equal(MilitaryRank.General, gear.Rank);
                        Assert.Equal("Modified Name", squad.Name);
                        Assert.Equal("Modified Name", weapon.Name);
                    }
                }
            });
        }
Example #26
0
        public void Inserting_entities_that_reference_themselves_in_a_cycle_throws()
        {
            ExtendedSqlAzureExecutionStrategy.ExecuteNew(
                () =>
            {
                using (new TransactionScope())
                {
                    using (var context = new GearsOfWarContext())
                    {
                        var snub = new StandardWeapon
                        {
                            Name  = "Snub",
                            Specs = new WeaponSpecification
                            {
                                AmmoPerClip = 12,
                                ClipsCount  = 11,
                            }
                        };

                        var sawedoff = new StandardWeapon
                        {
                            Name  = "Sawed-Off Shotgun",
                            Specs = new WeaponSpecification
                            {
                                AmmoPerClip = 1,
                                ClipsCount  = 6,
                            }
                        };

                        var longshot = new StandardWeapon
                        {
                            Name  = "Longshot",
                            Specs = new WeaponSpecification
                            {
                                AmmoPerClip = 1,
                                ClipsCount  = 24,
                            }
                        };

                        snub.SynergyWith     = sawedoff;
                        sawedoff.SynergyWith = longshot;
                        longshot.SynergyWith = snub;

                        context.Weapons.Add(snub);

                        Assert.Throws <DbUpdateException>(() => context.SaveChanges())
                        .InnerException.ValidateMessage(typeof(DbContext).Assembly(), "Update_ConstraintCycle", null);
                    }
                }
            });
        }
Example #27
0
 public void DbContext_SaveChangesAsync_does_not_deadlock()
 {
     ExtendedSqlAzureExecutionStrategy.ExecuteNew(
         () =>
     {
         using (var context = new SimpleModelContext())
         {
             using (context.Database.BeginTransaction())
             {
                 context.Products.Add(new Product());
                 RunDeadlockTest(context.SaveChangesAsync);
             }
         }
     });
 }
Example #28
0
        public void Verify_that_order_of_insert_is_based_on_key_values_and_not_order_of_adding_to_collection()
        {
            ExtendedSqlAzureExecutionStrategy.ExecuteNew(
                () =>
            {
                using (new TransactionScope())
                {
                    using (var context = new GearsOfWarContext())
                    {
                        var weapon1 = new HeavyWeapon
                        {
                            Id        = 10,
                            Name      = "Mortar",
                            Overheats = false,
                        };

                        var weapon2 = new HeavyWeapon
                        {
                            Id        = 11,
                            Name      = "Oneshot",
                            Overheats = false,
                        };

                        var weapon3 = new StandardWeapon
                        {
                            Id    = 12,
                            Name  = "Boltok",
                            Specs = new WeaponSpecification
                            {
                                AmmoPerClip = 6,
                                ClipsCount  = 9,
                            },
                        };

                        context.Weapons.Add(weapon3);
                        context.Weapons.Add(weapon1);
                        context.Weapons.Add(weapon2);
                        context.SaveChanges();

                        var newWeapons = context.Weapons.OrderByDescending(t => t.Id).Take(3).ToList();

                        Assert.Equal("Boltok", newWeapons[0].Name);
                        Assert.Equal("Oneshot", newWeapons[1].Name);
                        Assert.Equal("Mortar", newWeapons[2].Name);
                    }
                }
            });
        }
Example #29
0
        public override void EnsureDatabase()
        {
            ExtendedSqlAzureExecutionStrategy.ExecuteNew(
                () =>
            {
                var databaseExistsSql = "SELECT Count(*) FROM sys.databases WHERE name = N'" + _name + "'";
                var databaseExists    = ExecuteScalar <int>(databaseExistsSql, ModelHelpers.SimpleConnectionString("master")) == 1;
                if (!databaseExists)
                {
                    var createDatabaseSql = "CREATE DATABASE [" + _name + "]";
                    ExecuteNonQuery(createDatabaseSql, ModelHelpers.SimpleConnectionString("master"));
                }

                ResetDatabase();
            });
        }
            public void Can_insert_and_delete_when_many_to_many()
            {
                ExtendedSqlAzureExecutionStrategy.ExecuteNew(
                    () =>
                {
                    using (new TransactionScope())
                    {
                        using (var context = CreateContext())
                        {
                            var tag = new FunctionalTests.FunctionsScenarioTests.ModificationFunctions.Tag
                            {
                                Products = new List <FunctionalTests.FunctionsScenarioTests.ModificationFunctions.ProductA>
                                {
                                    new FunctionalTests.FunctionsScenarioTests.ModificationFunctions.ProductA()
                                }
                            };

                            Assert.Equal(
                                0,
                                context.Set <FunctionalTests.FunctionsScenarioTests.ModificationFunctions.Tag>()
                                .SelectMany(t => t.Products)
                                .Count());

                            // Insert
                            context.Set <FunctionalTests.FunctionsScenarioTests.ModificationFunctions.Tag>().Add(tag);
                            context.SaveChanges();

                            Assert.Equal(
                                1,
                                context.Set <FunctionalTests.FunctionsScenarioTests.ModificationFunctions.Tag>()
                                .SelectMany(t => t.Products)
                                .Count());

                            // Delete
                            tag.Products.Clear();
                            context.SaveChanges();

                            Assert.Equal(
                                0,
                                context.Set <FunctionalTests.FunctionsScenarioTests.ModificationFunctions.Tag>()
                                .SelectMany(t => t.Products)
                                .Count());
                        }
                    }
                });
            }