private static async Task Create_creates_physical_database_but_not_tables_test(bool async)
        {
            using (var testDatabase = await SqlServerTestDatabase.Scratch(createDatabase: false))
            {
                var creator = GetDataStoreCreator(testDatabase);

                Assert.False(creator.Exists());

                if (async)
                {
                    await creator.CreateAsync();
                }
                else
                {
                    creator.Create();
                }

                Assert.True(creator.Exists());

                if (testDatabase.Connection.State != ConnectionState.Open)
                {
                    await testDatabase.Connection.OpenAsync();
                }

                Assert.Equal(0, (await testDatabase.QueryAsync <string>("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES")).Count());

                Assert.True(await testDatabase.ExecuteScalarAsync <bool>(
                                string.Concat(
                                    "SELECT is_read_committed_snapshot_on FROM sys.databases WHERE name='",
                                    testDatabase.Connection.Database,
                                    "'"),
                                CancellationToken.None));
            }
        }
Beispiel #2
0
 private static async Task EnsureCreated_can_create_schema_in_existing_database_test(bool async)
 {
     using (var testDatabase = await SqlServerTestDatabase.Scratch())
     {
         await RunDatabaseCreationTest(testDatabase, async);
     }
 }
        private static async Task Can_use_an_existing_closed_connection_test(bool openConnection)
        {
            var serviceCollection = new ServiceCollection();

            serviceCollection
            .AddEntityFramework()
            .AddSqlServer()
            .UseLoggerFactory <LoggerFactory>();
            var serviceProvider = serviceCollection.BuildServiceProvider();

            using (await SqlServerTestDatabase.Northwind())
            {
                var openCount    = 0;
                var closeCount   = 0;
                var disposeCount = 0;

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

                    connection.StateChange += (_, a) =>
                    {
                        if (a.CurrentState == ConnectionState.Open)
                        {
                            openCount++;
                        }
                        else if (a.CurrentState == ConnectionState.Closed)
                        {
                            closeCount++;
                        }
                    };
#if !ASPNETCORE50
                    connection.Disposed += (_, __) => disposeCount++;
#endif

                    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);
                }
            }
        }
        private async Task Can_use_connection_string_name_in_OnConfiguring_test(string connectionName)
        {
            var configuration = new Configuration
            {
                new MemoryConfigurationSource(
                    new Dictionary <string, string>
                {
                    { "Data:Northwind:ConnectionString", SqlServerTestDatabase.NorthwindConnectionString }
                })
            };

            var serviceCollection = new ServiceCollection();

            serviceCollection
            .AddInstance <IConfiguration>(configuration)
            .AddEntityFramework()
            .AddSqlServer();

            var serviceProvider = serviceCollection.BuildServiceProvider();

            using (await SqlServerTestDatabase.Northwind())
            {
                using (var context = new NorthwindContext(serviceProvider, connectionName))
                {
                    Assert.Equal(91, await context.Customers.CountAsync());
                }
            }
        }
Beispiel #5
0
        private static async Task EnsureDeleted_will_delete_database_test(bool async)
        {
            using (var testDatabase = await SqlServerTestDatabase.Scratch(createDatabase: true))
            {
                testDatabase.Connection.Close();

                using (var context = new BloggingContext(testDatabase))
                {
                    Assert.True(async ? await context.Database.AsRelational().ExistsAsync() : context.Database.AsRelational().Exists());

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

                    Assert.Equal(ConnectionState.Closed, context.Database.AsRelational().Connection.DbConnection.State);

                    Assert.False(async ? await context.Database.AsRelational().ExistsAsync() : context.Database.AsRelational().Exists());

                    Assert.Equal(ConnectionState.Closed, context.Database.AsRelational().Connection.DbConnection.State);
                }
            }
        }
Beispiel #6
0
            public async Task Can_use_one_context_nested_inside_another_of_the_same_type()
            {
                using (await SqlServerTestDatabase.Northwind())
                {
                    var serviceCollection = new ServiceCollection();
                    serviceCollection.AddEntityFramework().AddSqlServer();
                    var serviceProvider = serviceCollection.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]);
                        }
                    }
                }
            }
Beispiel #7
0
 private static async Task EnsureCreated_can_create_physical_database_and_schema_test(bool async)
 {
     using (var testDatabase = await SqlServerTestDatabase.Scratch(createDatabase: false))
     {
         await RunDatabaseCreationTest(testDatabase, async);
     }
 }
Beispiel #8
0
        public async Task Can_run_linq_query_on_entity_set_with_value_buffer_reader()
        {
            using (await SqlServerTestDatabase.Northwind())
            {
                var serviceCollection = new ServiceCollection();
                serviceCollection.AddEntityFramework().AddSqlServer();
                serviceCollection.AddScoped <SqlServerDataStore, SqlStoreWithBufferReader>();
                var serviceProvider = serviceCollection.BuildServiceProvider();

                using (var db = new NorthwindContext(serviceProvider))
                {
                    var results = db.Customers
                                  .Where(c => c.CompanyName.StartsWith("A"))
                                  .OrderByDescending(c => c.CustomerID)
                                  .ToList();

                    Assert.Equal(4, results.Count);
                    Assert.Equal("AROUT", results[0].CustomerID);
                    Assert.Equal("ANTON", results[1].CustomerID);
                    Assert.Equal("ANATR", results[2].CustomerID);
                    Assert.Equal("ALFKI", results[3].CustomerID);

                    Assert.Equal("(171) 555-6750", results[0].Fax);
                    Assert.Null(results[1].Fax);
                    Assert.Equal("(5) 555-3745", results[2].Fax);
                    Assert.Equal("030-0076545", results[3].Fax);

                    Assert.IsType <SqlStoreWithBufferReader>(db.Configuration.DataStore);
                }
            }
        }
        private static async Task Create_creates_physical_database_but_not_tables_test(bool async)
        {
            using (var testDatabase = await SqlServerTestDatabase.Scratch(createDatabase: false))
            {
                var creator = GetDataStoreCreator(testDatabase);

                Assert.False(creator.Exists());

                if (async)
                {
                    await creator.CreateAsync();
                }
                else
                {
                    creator.Create();
                }

                Assert.True(creator.Exists());

                if (testDatabase.Connection.State != ConnectionState.Open)
                {
                    await testDatabase.Connection.OpenAsync();
                }

                Assert.Equal(0, (await testDatabase.QueryAsync <string>("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES")).Count());
            }
        }
Beispiel #10
0
 public async Task Can_use_one_context_nested_inside_another_of_a_different_type_with_implicit_services()
 {
     using (await SqlServerTestDatabase.Northwind())
     {
         await NestedContextTest(() => new BlogContext(), () => new NorthwindContext());
     }
 }
        public DbContext CreateContext(SqlServerTestDatabase testDatabase)
        {
            var options = new DbContextOptions()
                          .UseModel(SetTableNames(CreateModel()))
                          .UseSqlServer(testDatabase.Connection.ConnectionString);

            return(new DbContext(_serviceProvider, options));
        }
Beispiel #12
0
        private static async Task RunDatabaseCreationTest(SqlServerTestDatabase testDatabase, bool async)
        {
            using (var context = new BloggingContext(testDatabase))
            {
                Assert.Equal(ConnectionState.Closed, context.Database.AsRelational().Connection.DbConnection.State);

                if (async)
                {
                    Assert.True(await context.Database.AsRelational().EnsureCreatedAsync());
                }
                else
                {
                    Assert.True(context.Database.AsRelational().EnsureCreated());
                }

                Assert.Equal(ConnectionState.Closed, context.Database.AsRelational().Connection.DbConnection.State);

                if (testDatabase.Connection.State != ConnectionState.Open)
                {
                    await testDatabase.Connection.OpenAsync();
                }

                var tables = await testDatabase.QueryAsync <string>("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES");

                Assert.Equal(1, tables.Count());
                Assert.Equal("Blog", tables.Single());

                var columns = (await testDatabase.QueryAsync <string>(
                                   "SELECT TABLE_NAME + '.' + COLUMN_NAME + ' (' + DATA_TYPE + ')' FROM INFORMATION_SCHEMA.COLUMNS")).ToArray();
                Assert.Equal(19, columns.Length);

                Assert.Equal(
                    new[]
                {
                    "Blog.Key1 (nvarchar)",
                    "Blog.Key2 (varbinary)",
                    "Blog.AndChew (varbinary)",
                    "Blog.AndRow (timestamp)",
                    "Blog.Cheese (nvarchar)",
                    "Blog.CupOfChar (int)",
                    "Blog.ErMilan (int)",
                    "Blog.Fuse (smallint)",
                    "Blog.George (bit)",
                    "Blog.NotFigTime (datetime2)",
                    "Blog.NotToEat (smallint)",
                    "Blog.On (real)",
                    "Blog.OrNothing (float)",
                    "Blog.OrULong (int)",
                    "Blog.OrUShort (numeric)",
                    "Blog.OrUSkint (bigint)",
                    "Blog.TheGu (uniqueidentifier)",
                    "Blog.ToEat (tinyint)",
                    "Blog.WayRound (bigint)"
                },
                    columns);
            }
        }
        private static async Task HasTables_returns_false_when_database_exists_but_has_no_tables_test(bool async)
        {
            using (var testDatabase = await SqlServerTestDatabase.Scratch(createDatabase: true))
            {
                var creator = GetDataStoreCreator(testDatabase);

                Assert.False(async ? await creator.HasTablesAsync() : creator.HasTables());
            }
        }
Beispiel #14
0
        public async Task Can_save_changes_in_tracked_entities()
        {
            using (var testDatabase = await SqlServerTestDatabase.Scratch())
            {
                var options = new DbContextOptions().UseSqlServer(testDatabase.Connection.ConnectionString);

                int updatedId;
                int deletedId;
                int addedId;
                using (var db = new BloggingContext(options))
                {
                    var toAdd = db.Blogs.Add(new Blog()
                    {
                        Name       = "Blog to Insert",
                        George     = true,
                        TheGu      = new Guid("0456AEF1-B7FC-47AA-8102-975D6BA3A9BF"),
                        NotFigTime = new DateTime(1973, 9, 3, 0, 10, 33, 777),
                        ToEat      = 64,
                        OrNothing  = 0.123456789,
                        Fuse       = 777,
                        WayRound   = 9876543210,
                        Away       = 0.12345f,
                        AndChew    = new byte[16]
                    });
                    db.ChangeTracker.Entry(toAdd).State = EntityState.Unknown;

                    var blogs = await CreateBlogDatabaseAsync <Blog>(db);

                    var toUpdate = blogs[0];
                    toUpdate.Name = "Blog is Updated";
                    updatedId     = toUpdate.Id;
                    var toDelete = blogs[1];
                    toDelete.Name = "Blog to delete";
                    deletedId     = toDelete.Id;

                    db.Delete(toDelete);
                    db.ChangeTracker.Entry(toAdd).State = EntityState.Added;

                    await db.SaveChangesAsync();

                    addedId = toAdd.Id;
                    Assert.NotEqual(0, addedId);

                    Assert.Equal(EntityState.Unchanged, db.ChangeTracker.Entry(toUpdate).State);
                    Assert.Equal(EntityState.Unchanged, db.ChangeTracker.Entry(toAdd).State);
                    Assert.DoesNotContain(toDelete, db.ChangeTracker.Entries().Select(e => e.Entity));
                }

                using (var db = new BloggingContext(options))
                {
                    var toUpdate = db.Blogs.Single(b => b.Id == updatedId);
                    Assert.Equal("Blog is Updated", toUpdate.Name);
                    Assert.Equal(0, db.Blogs.Count(b => b.Id == deletedId));
                    Assert.Equal("Blog to Insert", db.Blogs.Single(b => b.Id == addedId).Name);
                }
            }
        }
        private static async Task Exists_returns_true_when_database_exists_test(bool async)
        {
            using (var testDatabase = await SqlServerTestDatabase.Scratch(createDatabase: true))
            {
                var creator = GetDataStoreCreator(testDatabase);

                Assert.True(async ? await creator.ExistsAsync() : creator.Exists());
            }
        }
Beispiel #16
0
 public async Task Can_query_with_implicit_services_and_OnConfiguring()
 {
     using (await SqlServerTestDatabase.Northwind())
     {
         using (var context = new NorthwindContext())
         {
             Assert.Equal(91, await context.Customers.CountAsync());
         }
     }
 }
Beispiel #17
0
 public async Task Can_pass_connection_string_to_constructor_and_use_in_OnConfiguring()
 {
     using (await SqlServerTestDatabase.Northwind())
     {
         using (var context = new NorthwindContext(SqlServerTestDatabase.NorthwindConnectionString))
         {
             Assert.Equal(91, await context.Customers.CountAsync());
         }
     }
 }
Beispiel #18
0
 public async Task Can_pass_connection_string_to_constructor_and_use_in_builder()
 {
     using (await SqlServerTestDatabase.Northwind())
     {
         using (var context = new NorthwindContext(SqlServerTestDatabase.NorthwindConnectionString))
         {
             Assert.Equal(91, await QueryableExtensions.CountAsync(context.Customers));
         }
     }
 }
        private static DbContextConfiguration CreateConfiguration(SqlServerTestDatabase testDatabase)
        {
            var serviceCollection = new ServiceCollection();

            serviceCollection.AddEntityFramework().AddSqlServer();
            return(new DbContext(
                       serviceCollection.BuildServiceProvider(),
                       new DbContextOptions().UseSqlServer(testDatabase.Connection.ConnectionString))
                   .Configuration);
        }
        private static async Task HasTables_returns_true_when_database_exists_and_has_any_tables_test(bool async)
        {
            using (var testDatabase = await SqlServerTestDatabase.Scratch(createDatabase: true))
            {
                await testDatabase.ExecuteNonQueryAsync("CREATE TABLE SomeTable (Id uniqueidentifier)");

                var creator = GetDataStoreCreator(testDatabase);

                Assert.True(async ? await creator.HasTablesAsync() : creator.HasTables());
            }
        }
Beispiel #21
0
        public async Task Can_execute_scalar_command()
        {
            using (var testDatabase = await SqlServerTestDatabase.Default())
            {
                var commandExecutor = new SqlServerSimpleCommandExecutor(testDatabase.Connection.ConnectionString);

                var scalar = await commandExecutor.ExecuteScalarAsync <int>("select 42", CancellationToken.None);

                Assert.Equal(42, scalar);
            }
        }
Beispiel #22
0
            public async Task Can_use_one_context_nested_inside_another_of_a_different_type()
            {
                using (await SqlServerTestDatabase.Northwind())
                {
                    var serviceCollection = new ServiceCollection();
                    serviceCollection.AddEntityFramework().AddSqlServer().AddInMemoryStore();
                    var serviceProvider = serviceCollection.BuildServiceProvider();

                    await NestedContextTest(() => new BlogContext(serviceProvider), () => new NorthwindContext(serviceProvider));
                }
            }
Beispiel #23
0
            public async Task Can_query_with_implicit_services_and_explicit_config()
            {
                using (await SqlServerTestDatabase.Northwind())
                {
                    var options = new DbContextOptions().UseSqlServer(SqlServerTestDatabase.NorthwindConnectionString);

                    using (var context = new NorthwindContext(options))
                    {
                        Assert.Equal(91, await context.Customers.CountAsync());
                    }
                }
            }
Beispiel #24
0
        private static async Task Exists_returns_true_when_database_exists_test(bool async)
        {
            using (var testDatabase = await SqlServerTestDatabase.Scratch(createDatabase: true))
            {
                using (var context = new BloggingContext(testDatabase))
                {
                    Assert.True(async ? await context.Database.AsRelational().ExistsAsync() : context.Database.AsRelational().Exists());

                    Assert.Equal(ConnectionState.Closed, context.Database.AsRelational().Connection.DbConnection.State);
                }
            }
        }
        private static async Task Delete_throws_when_database_doesnt_exist_test(bool async)
        {
            using (var testDatabase = await SqlServerTestDatabase.Scratch(createDatabase: false))
            {
                var creator = GetDataStoreCreator(testDatabase);

                Assert.Equal(
                    3701, // Database does not exist
                    async
                        ? (await Assert.ThrowsAsync <SqlException>(() => creator.DeleteAsync())).Number
                        : Assert.Throws <SqlException>(() => creator.Delete()).Number);
            }
        }
        private static async Task Create_throws_if_database_already_exists_test(bool async)
        {
            using (var testDatabase = await SqlServerTestDatabase.Scratch(createDatabase: true))
            {
                var creator = GetDataStoreCreator(testDatabase);

                Assert.Equal(
                    1801, // Database with given name already exists
                    async
                        ? (await Assert.ThrowsAsync <SqlException>(() => creator.CreateAsync())).Number
                        : Assert.Throws <SqlException>(() => creator.Create()).Number);
            }
        }
Beispiel #27
0
            public async Task Can_query_with_explicit_services_and_OnConfiguring()
            {
                using (await SqlServerTestDatabase.Northwind())
                {
                    var serviceCollection = new ServiceCollection();
                    serviceCollection.AddEntityFramework().AddSqlServer();
                    var serviceProvider = serviceCollection.BuildServiceProvider();

                    using (var context = new NorthwindContext(serviceProvider))
                    {
                        Assert.Equal(91, await context.Customers.CountAsync());
                    }
                }
            }
        public override DbContext CreateContext()
        {
            var testDatabase = SqlServerTestDatabase.Scratch().Result;

            var options
                = new DbContextOptions()
                  .UseModel(CreateModel())
                  .UseSqlServer(testDatabase.Connection.ConnectionString);

            var context = new DbContext(options);

            context.Database.EnsureCreated();
            return(context);
        }
Beispiel #29
0
            public async Task Can_register_context_with_DI_container_and_have_it_injected()
            {
                var serviceCollection = new ServiceCollection();

                serviceCollection.AddEntityFramework().AddSqlServer();
                var serviceProvider = serviceCollection
                                      .AddTransient <NorthwindContext>()
                                      .AddTransient <MyController>()
                                      .BuildServiceProvider();

                using (await SqlServerTestDatabase.Northwind())
                {
                    await serviceProvider.GetService <MyController>().TestAsync();
                }
            }
Beispiel #30
0
 public async Task Throws_on_attempt_to_use_context_with_no_store()
 {
     using (await SqlServerTestDatabase.Northwind())
     {
         Assert.Equal(
             GetString("FormatNoDataStoreConfigured"),
             Assert.Throws <InvalidOperationException>(() =>
         {
             using (var context = new NorthwindContext())
             {
                 Assert.Equal(91, context.Customers.Count());
             }
         }).Message);
     }
 }