public void Insert_with_Identity_column()
        {
            using (var testStore = MySqlTestStore.CreateInitialized(DatabaseName))
            {
                using (var context = new BlogContextIdentity(testStore.Name))
                {
                    context.Database.EnsureCreated();

                    context.AddRange(new Blog {
                        Name = "One Unicorn"
                    }, new Blog {
                        Name = "Two Unicorns"
                    });

                    context.SaveChanges();
                }

                using (var context = new BlogContextIdentity(testStore.Name))
                {
                    var blogs = context.Blogs.OrderBy(e => e.Id).ToList();

                    Assert.Equal(1, blogs[0].Id);
                    Assert.Equal(2, blogs[1].Id);
                }
            }
        }
        public void Insert_with_default_string_value_from_sequence()
        {
            using (var testStore = MySqlTestStore.CreateInitialized(DatabaseName))
            {
                using (var context = new BlogContextStringDefaultValue(testStore.Name))
                {
                    context.Database.EnsureCreated();

                    context.AddRange(new BlogWithStringKey {
                        Name = "One Unicorn"
                    }, new BlogWithStringKey {
                        Name = "Two Unicorns"
                    });

                    context.SaveChanges();
                }

                using (var context = new BlogContextStringDefaultValue(testStore.Name))
                {
                    var blogs = context.StringyBlogs.OrderBy(e => e.Id).ToList();

                    Assert.Equal("i77", blogs[0].Id);
                    Assert.Equal("i78", blogs[1].Id);
                }
            }
        }
        public void Insert_with_explicit_with_default_keys()
        {
            using (var testStore = MySqlTestStore.CreateInitialized(DatabaseName))
            {
                using (var context = new BlogContextNoKeyGenerationNullableKey(testStore.Name))
                {
                    context.Database.EnsureCreatedResiliently();

                    context.AddRange(
                        new NullableKeyBlog
                    {
                        Id   = 0,
                        Name = "One Unicorn"
                    },
                        new NullableKeyBlog
                    {
                        Id   = 1,
                        Name = "Two Unicorns"
                    });

                    context.SaveChanges();
                }

                using (var context = new BlogContextNoKeyGenerationNullableKey(testStore.Name))
                {
                    var blogs = context.NullableKeyBlogs.OrderBy(e => e.Id).ToList();

                    Assert.Equal(0, blogs[0].Id);
                    Assert.Equal(1, blogs[1].Id);
                }
            }
        }
        public void Insert_with_key_default_value_from_sequence()
        {
            using (var testStore = MySqlTestStore.CreateInitialized(DatabaseName))
            {
                using (var context = new BlogContextKeyColumnWithDefaultValue(testStore.Name))
                {
                    context.Database.EnsureCreatedResiliently();

                    context.AddRange(
                        new Blog
                    {
                        Name = "One Unicorn"
                    }, new Blog
                    {
                        Name = "Two Unicorns"
                    });

                    context.SaveChanges();
                }

                using (var context = new BlogContextKeyColumnWithDefaultValue(testStore.Name))
                {
                    var blogs = context.Blogs.OrderBy(e => e.Id).ToList();

                    Assert.Equal(77, blogs[0].Id);
                    Assert.Equal(78, blogs[1].Id);
                }
            }
        }
        public void Insert_and_update_with_computed_column()
        {
            using (var testStore = MySqlTestStore.CreateInitialized(DatabaseName))
            {
                using (var context = new BlogContextComputedColumn(testStore.Name))
                {
                    context.Database.EnsureCreatedResiliently();

                    var blog = context.Add(
                        new FullNameBlog
                    {
                        FirstName = "One",
                        LastName  = "Unicorn"
                    }).Entity;

                    context.SaveChanges();

                    Assert.Equal("One Unicorn", blog.FullName);
                }

                using (var context = new BlogContextComputedColumn(testStore.Name))
                {
                    var blog = context.FullNameBlogs.Single();

                    Assert.Equal("One Unicorn", blog.FullName);

                    blog.LastName = "Pegasus";

                    context.SaveChanges();

                    Assert.Equal("One Pegasus", blog.FullName);
                }
            }
        }
        private static async Task Returns_true_when_database_exists_test(bool async, bool ambientTransaction, bool useCanConnect, bool file)
        {
            using (var testDatabase = file
                ? MySqlTestStore.CreateInitialized("ExistingBloggingFile", useFileName: true)
                : MySqlTestStore.GetOrCreateInitialized("ExistingBlogging"))
            {
                using (var context = new BloggingContext(testDatabase))
                {
                    var creator = GetDatabaseCreator(context);
                    using (CreateTransactionScope(ambientTransaction))
                    {
                        if (useCanConnect)
                        {
                            Assert.True(async ? await creator.CanConnectAsync() : creator.CanConnect());
                        }
                        else
                        {
                            Assert.True(async ? await creator.ExistsAsync() : creator.Exists());
                        }
                    }

                    Assert.Equal(ConnectionState.Closed, context.Database.GetDbConnection().State);
                }
            }
        }
        public void Insert_with_sequence_HiLo()
        {
            using (var testStore = MySqlTestStore.CreateInitialized(DatabaseName))
            {
                using (var context = new BlogContextHiLo(testStore.Name))
                {
                    context.Database.EnsureCreatedResiliently();

                    context.AddRange(
                        new Blog
                    {
                        Name = "One Unicorn"
                    }, new Blog
                    {
                        Name = "Two Unicorns"
                    });

                    context.SaveChanges();
                }

                using (var context = new BlogContextHiLo(testStore.Name))
                {
                    var blogs = context.Blogs.OrderBy(e => e.Id).ToList();

                    Assert.Equal(1, blogs[0].Id);
                    Assert.Equal(2, blogs[0].OtherId);
                    Assert.Equal(3, blogs[1].Id);
                    Assert.Equal(4, blogs[1].OtherId);
                }
            }
        }
        public static async Task Deletes_database(bool async, bool ambientTransaction)
        {
            using (var testDatabase = MySqlTestStore.CreateInitialized("DeleteBlogging"))
            {
                testDatabase.CloseConnection();

                var creator = GetDatabaseCreator(testDatabase);

                Assert.True(async ? await creator.ExistsAsync() : creator.Exists());

                using (CreateTransactionScope(ambientTransaction))
                {
                    if (async)
                    {
                        await creator.DeleteAsync();
                    }
                    else
                    {
                        creator.Delete();
                    }
                }

                Assert.False(async ? await creator.ExistsAsync() : creator.Exists());
            }
        }
        public void Can_use_AddDbContext_and_get_connection_string_from_config(string key, string connectionString)
        {
            var configBuilder = new ConfigurationBuilder()
                                .AddInMemoryCollection(
                new Dictionary <string, string>
            {
                { key, MySqlNorthwindTestStoreFactory.NorthwindConnectionString }
            });

            var serviceProvider
                = new ServiceCollection()
                  .AddSingleton <IConfiguration>(configBuilder.Build())
                  .AddDbContext <UseConfigurationContext>(
                      b => b.UseMySql(connectionString))
                  .BuildServiceProvider();

            using (MySqlTestStore.GetNorthwindStore())
            {
                using (var serviceScope = serviceProvider.GetRequiredService <IServiceScopeFactory>().CreateScope())
                {
                    using (var context = serviceScope.ServiceProvider.GetRequiredService <UseConfigurationContext>())
                    {
                        Assert.True(context.Customers.Any());
                    }
                }
            }
        }
        private static async Task Noop_when_database_does_not_exist_test(bool async, bool file)
        {
            using (var testDatabase = MySqlTestStore.Create("NonExisting", file))
            {
                using (var context = new BloggingContext(testDatabase))
                {
                    var creator = GetDatabaseCreator(context);

                    Assert.False(async ? await creator.ExistsAsync() : creator.Exists());

                    if (async)
                    {
                        Assert.False(await creator.EnsureDeletedAsync());
                    }
                    else
                    {
                        Assert.False(creator.EnsureDeleted());
                    }

                    Assert.Equal(ConnectionState.Closed, context.Database.GetDbConnection().State);

                    Assert.False(async ? await creator.ExistsAsync() : creator.Exists());

                    Assert.Equal(ConnectionState.Closed, context.Database.GetDbConnection().State);
                }
            }
        }
        private static async Task Delete_database_test(bool async, bool open, bool ambientTransaction, bool file)
        {
            using (var testDatabase = MySqlTestStore.CreateInitialized("EnsureDeleteBlogging" + (file ? "File" : ""), file))
            {
                if (!open)
                {
                    testDatabase.CloseConnection();
                }

                using (var context = new BloggingContext(testDatabase))
                {
                    var creator = GetDatabaseCreator(context);

                    Assert.True(async ? await creator.ExistsAsync() : creator.Exists());

                    using (CreateTransactionScope(ambientTransaction))
                    {
                        if (async)
                        {
                            Assert.True(await context.Database.EnsureDeletedAsync());
                        }
                        else
                        {
                            Assert.True(context.Database.EnsureDeleted());
                        }
                    }

                    Assert.Equal(ConnectionState.Closed, context.Database.GetDbConnection().State);

                    Assert.False(async ? await creator.ExistsAsync() : creator.Exists());

                    Assert.Equal(ConnectionState.Closed, context.Database.GetDbConnection().State);
                }
            }
        }
コード例 #12
0
            public async Task Can_use_one_context_nested_inside_another_of_the_same_type()
            {
                using (MySqlTestStore.GetNorthwindStore())
                {
                    var serviceProvider = new ServiceCollection()
                                          .AddEntityFrameworkMySql()
                                          .BuildServiceProvider();

                    using (var context1 = new NorthwindContext(serviceProvider))
                    {
                        var customers1 = await context1.Customers.ToListAsync();

                        Assert.Equal(91, customers1.Count);
                        Assert.Equal(91, context1.ChangeTracker.Entries().Count());

                        using (var context2 = new NorthwindContext(serviceProvider))
                        {
                            Assert.Equal(0, context2.ChangeTracker.Entries().Count());

                            var customers2 = await context2.Customers.ToListAsync();

                            Assert.Equal(91, customers2.Count);
                            Assert.Equal(91, context2.ChangeTracker.Entries().Count());

                            Assert.Equal(customers1[0].CustomerID, customers2[0].CustomerID);
                            Assert.NotSame(customers1[0], customers2[0]);
                        }
                    }
                }
            }
コード例 #13
0
        private static async Task Returns_false_when_database_does_not_exist_test(
            bool async, bool ambientTransaction, bool useCanConnect, bool file)
        {
            using (var testDatabase = MySqlTestStore.Create("NonExisting", file))
            {
                using (var context = new BloggingContext(testDatabase))
                {
                    var creator = GetDatabaseCreator(context);

                    using (CreateTransactionScope(ambientTransaction))
                    {
                        if (useCanConnect)
                        {
                            Assert.False(async ? await creator.CanConnectAsync() : creator.CanConnect());
                        }
                        else
                        {
                            Assert.False(async ? await creator.ExistsAsync() : creator.Exists());
                        }
                    }

                    Assert.Equal(ConnectionState.Closed, context.Database.GetDbConnection().State);
                }
            }
        }
コード例 #14
0
        private static async Task Can_use_an_existing_closed_connection_test(bool openConnection)
        {
            var serviceProvider = new ServiceCollection()
                                  .AddEntityFrameworkMySql()
                                  .BuildServiceProvider();

            using (var store = MySqlTestStore.GetNorthwindStore())
            {
                store.CloseConnection();

                var openCount    = 0;
                var closeCount   = 0;
                var disposeCount = 0;

                using (var connection = new SqlConnection(store.ConnectionString))
                {
                    if (openConnection)
                    {
                        await connection.OpenAsync();
                    }

                    connection.StateChange += (_, a) =>
                    {
                        switch (a.CurrentState)
                        {
                        case ConnectionState.Open:
                            openCount++;
                            break;

                        case ConnectionState.Closed:
                            closeCount++;
                            break;
                        }
                    };
                    connection.Disposed += (_, __) => disposeCount++;

                    using (var context = new NorthwindContext(serviceProvider, connection))
                    {
                        Assert.Equal(91, await context.Customers.CountAsync());
                    }

                    if (openConnection)
                    {
                        Assert.Equal(ConnectionState.Open, connection.State);
                        Assert.Equal(0, openCount);
                        Assert.Equal(0, closeCount);
                    }
                    else
                    {
                        Assert.Equal(ConnectionState.Closed, connection.State);
                        Assert.Equal(1, openCount);
                        Assert.Equal(1, closeCount);
                    }

                    Assert.Equal(0, disposeCount);
                }
            }
        }
コード例 #15
0
 public async Task Can_pass_connection_string_to_constructor_and_use_in_OnConfiguring()
 {
     using (MySqlTestStore.GetNorthwindStore())
     {
         using (var context = new NorthwindContext(MySqlNorthwindTestStoreFactory.NorthwindConnectionString))
         {
             Assert.Equal(91, await context.Customers.CountAsync());
         }
     }
 }
 public void Can_specify_connection_in_OnConfiguring_with_default_service_provider()
 {
     using (MySqlTestStore.GetNorthwindStore())
     {
         using (var context = new ConnectionInOnConfiguringContext(new SqlConnection(MySqlNorthwindTestStoreFactory.NorthwindConnectionString)))
         {
             Assert.True(context.Customers.Any());
         }
     }
 }
 public void Can_depend_on_non_generic_options_when_only_one_context_with_default_service_provider()
 {
     using (MySqlTestStore.GetNorthwindStore())
     {
         using (var context = new NonGenericOptionsContext(new DbContextOptions <DbContext>()))
         {
             Assert.True(context.Customers.Any());
         }
     }
 }
コード例 #18
0
 public async Task Can_query_with_implicit_services_and_OnConfiguring()
 {
     using (MySqlTestStore.GetNorthwindStore())
     {
         using (var context = new NorthwindContext())
         {
             Assert.Equal(91, await context.Customers.CountAsync());
         }
     }
 }
 public async Task Returns_false_when_database_exists_but_has_no_tables(bool async, bool ambientTransaction)
 {
     using (var testDatabase = MySqlTestStore.GetOrCreateInitialized("Empty"))
     {
         var creator = GetDatabaseCreator(testDatabase);
         using (CreateTransactionScope(ambientTransaction))
         {
             Assert.False(async ? await creator.HasTablesAsyncBase() : creator.HasTablesBase());
         }
     }
 }
コード例 #20
0
        protected override DbContext CreateContextWithConnectionString()
        {
            var options = Fixture.AddOptions(
                new DbContextOptionsBuilder()
                .UseMySql(
                    TestStore.ConnectionString,
                    b => MySqlTestStore.AddOptions(b).ExecutionStrategy(c => new MySqlExecutionStrategy(c))))
                          .UseInternalServiceProvider(Fixture.ServiceProvider);

            return(new DbContext(options.Options));
        }
コード例 #21
0
 public async Task Can_query_with_implicit_services_and_explicit_config()
 {
     using (MySqlTestStore.GetNorthwindStore())
     {
         using (var context = new NorthwindContext(
                    new DbContextOptionsBuilder()
                    .UseMySql(MySqlNorthwindTestStoreFactory.NorthwindConnectionString, b => b.ApplyConfiguration()).Options))
         {
             Assert.Equal(91, await context.Customers.CountAsync());
         }
     }
 }
 public void Can_depend_on_DbContextOptions_with_default_service_provider()
 {
     using (MySqlTestStore.GetNorthwindStore())
     {
         using (var context = new OptionsContext(
                    new DbContextOptions <OptionsContext>(),
                    new SqlConnection(MySqlNorthwindTestStoreFactory.NorthwindConnectionString)))
         {
             Assert.True(context.Customers.Any());
         }
     }
 }
 public async Task Returns_true_when_database_exists_and_has_any_tables(bool async, bool ambientTransaction)
 {
     using (var testDatabase = MySqlTestStore.GetOrCreate("ExistingTables")
                               .InitializeMySql(null, t => new BloggingContext(t), null))
     {
         var creator = GetDatabaseCreator(testDatabase);
         using (CreateTransactionScope(ambientTransaction))
         {
             Assert.True(async ? await creator.HasTablesAsyncBase() : creator.HasTablesBase());
         }
     }
 }
        public void Insert_with_non_key_default_value()
        {
            using (var testStore = MySqlTestStore.CreateInitialized(DatabaseName))
            {
                using (var context = new BlogContextNonKeyDefaultValue(testStore.Name))
                {
                    context.Database.EnsureCreatedResiliently();

                    var blogs = new List <Blog>
                    {
                        new Blog
                        {
                            Name = "One Unicorn"
                        },
                        new Blog
                        {
                            Name      = "Two Unicorns",
                            CreatedOn = new DateTime(1969, 8, 3, 0, 10, 0)
                        }
                    };

                    context.AddRange(blogs);

                    context.SaveChanges();

                    Assert.NotEqual(new DateTime(), blogs[0].CreatedOn);
                    Assert.NotEqual(new DateTime(), blogs[1].CreatedOn);
                    Assert.Null(blogs[0].OtherId);
                    Assert.Null(blogs[1].OtherId);
                }

                using (var context = new BlogContextNonKeyDefaultValue(testStore.Name))
                {
                    var blogs = context.Blogs.OrderBy(e => e.Name).ToList();

                    Assert.NotEqual(new DateTime(), blogs[0].CreatedOn);
                    Assert.Equal(new DateTime(1969, 8, 3, 0, 10, 0), blogs[1].CreatedOn);

                    blogs[0].CreatedOn = new DateTime(1973, 9, 3, 0, 10, 0);
                    blogs[1].Name      = "Zwo Unicorns";

                    context.SaveChanges();
                }

                using (var context = new BlogContextNonKeyDefaultValue(testStore.Name))
                {
                    var blogs = context.Blogs.OrderBy(e => e.Name).ToList();

                    Assert.Equal(new DateTime(1969, 8, 3, 0, 10, 0), blogs[1].CreatedOn);
                    Assert.Equal(new DateTime(1973, 9, 3, 0, 10, 0), blogs[0].CreatedOn);
                }
            }
        }
コード例 #25
0
 public async Task Can_pass_context_options_to_constructor_and_use_in_builder()
 {
     using (MySqlTestStore.GetNorthwindStore())
     {
         using (var context = new NorthwindContext(
                    new DbContextOptionsBuilder()
                    .UseMySql(MySqlNorthwindTestStoreFactory.NorthwindConnectionString, b => b.ApplyConfiguration()).Options))
         {
             Assert.Equal(91, await context.Customers.CountAsync());
         }
     }
 }
        public async Task Creates_schema_in_existing_database_test(bool async, bool ambientTransaction)
        {
            using (var testDatabase = MySqlTestStore.GetOrCreateInitialized("ExistingBlogging" + (async ? "Async" : "")))
            {
                using (var context = new BloggingContext(testDatabase))
                {
                    var creator = GetDatabaseCreator(context);

                    using (CreateTransactionScope(ambientTransaction))
                    {
                        if (async)
                        {
                            await creator.CreateTablesAsync();
                        }
                        else
                        {
                            creator.CreateTables();
                        }
                    }

                    if (testDatabase.ConnectionState != ConnectionState.Open)
                    {
                        await testDatabase.OpenConnectionAsync();
                    }

                    var tables = (await testDatabase.QueryAsync <string>(
                                      "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE'")).ToList();
                    Assert.Equal(1, tables.Count);
                    Assert.Equal("Blogs", tables.Single());

                    var columns = (await testDatabase.QueryAsync <string>(
                                       "SELECT TABLE_NAME + '.' + COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Blogs'")).ToList();
                    Assert.Equal(14, columns.Count);
                    Assert.True(columns.Any(c => c == "Blogs.Key1"));
                    Assert.True(columns.Any(c => c == "Blogs.Key2"));
                    Assert.True(columns.Any(c => c == "Blogs.Cheese"));
                    Assert.True(columns.Any(c => c == "Blogs.ErMilan"));
                    Assert.True(columns.Any(c => c == "Blogs.George"));
                    Assert.True(columns.Any(c => c == "Blogs.TheGu"));
                    Assert.True(columns.Any(c => c == "Blogs.NotFigTime"));
                    Assert.True(columns.Any(c => c == "Blogs.ToEat"));
                    Assert.True(columns.Any(c => c == "Blogs.OrNothing"));
                    Assert.True(columns.Any(c => c == "Blogs.Fuse"));
                    Assert.True(columns.Any(c => c == "Blogs.WayRound"));
                    Assert.True(columns.Any(c => c == "Blogs.On"));
                    Assert.True(columns.Any(c => c == "Blogs.AndChew"));
                    Assert.True(columns.Any(c => c == "Blogs.AndRow"));
                }
            }
        }
コード例 #27
0
            public async Task Can_register_context_with_DI_container_and_have_it_injected()
            {
                var serviceProvider = new ServiceCollection()
                                      .AddEntityFrameworkMySql()
                                      .AddTransient <NorthwindContext>()
                                      .AddTransient <MyController>()
                                      .AddSingleton(p => new DbContextOptionsBuilder().UseInternalServiceProvider(p).Options)
                                      .BuildServiceProvider();

                using (MySqlTestStore.GetNorthwindStore())
                {
                    await serviceProvider.GetRequiredService <MyController>().TestAsync();
                }
            }
コード例 #28
0
            public async Task Can_register_context_and_configuration_with_DI_container_and_have_both_injected()
            {
                var serviceProvider = new ServiceCollection()
                                      .AddTransient <MyController>()
                                      .AddTransient <NorthwindContext>()
                                      .AddSingleton(
                    new DbContextOptionsBuilder()
                    .UseMySql(MySqlNorthwindTestStoreFactory.NorthwindConnectionString, b => b.ApplyConfiguration()).Options).BuildServiceProvider();

                using (MySqlTestStore.GetNorthwindStore())
                {
                    await serviceProvider.GetRequiredService <MyController>().TestAsync();
                }
            }
コード例 #29
0
 public async Task Can_query_with_explicit_services_and_OnConfiguring()
 {
     using (MySqlTestStore.GetNorthwindStore())
     {
         using (var context = new NorthwindContext(
                    new DbContextOptionsBuilder().UseInternalServiceProvider(
                        new ServiceCollection()
                        .AddEntityFrameworkMySql()
                        .BuildServiceProvider()).Options))
         {
             Assert.Equal(91, await context.Customers.CountAsync());
         }
     }
 }
        public void Insert_with_non_key_default_value_readonly()
        {
            using (var testStore = MySqlTestStore.CreateInitialized(DatabaseName))
            {
                using (var context = new BlogContextNonKeyReadOnlyDefaultValue(testStore.Name))
                {
                    context.Database.EnsureCreatedResiliently();

                    context.AddRange(
                        new Blog
                    {
                        Name = "One Unicorn"
                    },
                        new Blog
                    {
                        Name = "Two Unicorns"
                    });

                    context.SaveChanges();

                    Assert.NotEqual(new DateTime(), context.Blogs.ToList()[0].CreatedOn);
                }

                DateTime dateTime0;

                using (var context = new BlogContextNonKeyReadOnlyDefaultValue(testStore.Name))
                {
                    var blogs = context.Blogs.OrderBy(e => e.Id).ToList();

                    dateTime0 = blogs[0].CreatedOn;

                    Assert.NotEqual(new DateTime(), dateTime0);
                    Assert.NotEqual(new DateTime(), blogs[1].CreatedOn);

                    blogs[0].Name      = "One Pegasus";
                    blogs[1].CreatedOn = new DateTime(1973, 9, 3, 0, 10, 0);

                    context.SaveChanges();
                }

                using (var context = new BlogContextNonKeyReadOnlyDefaultValue(testStore.Name))
                {
                    var blogs = context.Blogs.OrderBy(e => e.Id).ToList();

                    Assert.Equal(dateTime0, blogs[0].CreatedOn);
                    Assert.Equal(new DateTime(1973, 9, 3, 0, 10, 0), blogs[1].CreatedOn);
                }
            }
        }