Пример #1
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);
     }
 }
Пример #2
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);
     }
 }
        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));
            }
        }
        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());
            }
        }
Пример #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);
                }
            }
        }
        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());
            }
        }
        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());
            }
        }
Пример #8
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 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());
            }
        }
Пример #10
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 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);
            }
        }
        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);
            }
        }
Пример #13
0
        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);
        }
        private static async Task HasTables_throws_when_database_doesnt_exist_test(bool async)
        {
            using (var testDatabase = await SqlServerTestDatabase.Scratch(createDatabase: false))
            {
                var creator = GetDataStoreCreator(testDatabase);

                var errorNumber = async
                    ? (await Assert.ThrowsAsync <SqlException>(() => creator.HasTablesAsync())).Number
                    : Assert.Throws <SqlException>(() => creator.HasTables()).Number;

                if (errorNumber != 233) // skip if no-process transient failure
                {
                    Assert.Equal(
                        4060, // Login failed error number
                        errorNumber);
                }
            }
        }
        private static async Task CreateTables_creates_schema_in_existing_database_test(bool async)
        {
            using (var testDatabase = await SqlServerTestDatabase.Scratch())
            {
                var serviceCollection = new ServiceCollection();
                serviceCollection
                .AddEntityFramework()
                .AddSqlServer()
                .UseLoggerFactory <LoggerFactory>();
                var serviceProvider = serviceCollection.BuildServiceProvider();

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

                using (var context = new BloggingContext(serviceProvider, options))
                {
                    var creator = (RelationalDataStoreCreator)context.Configuration.DataStoreCreator;

                    if (async)
                    {
                        await creator.CreateTablesAsync(context.Model);
                    }
                    else
                    {
                        creator.CreateTables(context.Model);
                    }

                    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 FROM INFORMATION_SCHEMA.COLUMNS");

                    Assert.Equal(2, columns.Count());
                    Assert.True(columns.Any(c => c == "Blog.Id"));
                    Assert.True(columns.Any(c => c == "Blog.Name"));
                }
            }
        }
Пример #16
0
        private static async Task EnsuredCreated_is_noop_when_database_exists_and_has_schema_test(bool async)
        {
            using (var testDatabase = await SqlServerTestDatabase.Scratch(createDatabase: false))
            {
                using (var context = new BloggingContext(testDatabase))
                {
                    context.Database.EnsureCreated();

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

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

                var creator = GetDataStoreCreator(testDatabase);

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

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

                Assert.False(async ? await creator.ExistsAsync() : creator.Exists());
            }
        }
Пример #18
0
        private async Task RoundTripChanges <TBlog>() where TBlog : class, IBlog, new()
        {
            using (var testDatabase = await SqlServerTestDatabase.Scratch())
            {
                var options = new DbContextOptions().UseSqlServer(testDatabase.Connection.ConnectionString);

                int blog1Id;
                int blog2Id;
                int blog3Id;

                using (var context = new BloggingContext <TBlog>(options))
                {
                    var blogs = await CreateBlogDatabaseAsync <TBlog>(context);

                    blog1Id = blogs[0].Id;
                    blog2Id = blogs[1].Id;

                    Assert.NotEqual(0, blog1Id);
                    Assert.NotEqual(0, blog2Id);
                    Assert.NotEqual(blog1Id, blog2Id);
                }

                using (var context = new BloggingContext <TBlog>(options))
                {
                    var blogs = context.Blogs.ToList();
                    Assert.Equal(2, blogs.Count);

                    var blog1 = blogs.Single(b => b.Name == "Blog1");
                    Assert.Equal(blog1Id, blog1.Id);

                    Assert.Equal("Blog1", blog1.Name);
                    Assert.True(blog1.George);
                    Assert.Equal(new Guid("0456AEF1-B7FC-47AA-8102-975D6BA3A9BF"), blog1.TheGu);
                    Assert.Equal(new DateTime(1973, 9, 3, 0, 10, 33, 777), blog1.NotFigTime);
                    Assert.Equal(64, blog1.ToEat);
                    Assert.Equal(0.123456789, blog1.OrNothing);
                    Assert.Equal(777, blog1.Fuse);
                    Assert.Equal(9876543210, blog1.WayRound);
                    Assert.Equal(0.12345f, blog1.Away);
                    Assert.Equal(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }, blog1.AndChew);

                    blog1.Name = "New Name";

                    var blog2 = blogs.Single(b => b.Name == "Blog2");
                    Assert.Equal(blog2Id, blog2.Id);

                    blog2.Name       = null;
                    blog2.NotFigTime = new DateTime();
                    blog2.AndChew    = null;

                    var blog3 = context.Add(new TBlog());

                    await context.SaveChangesAsync();

                    blog3Id = blog3.Id;
                    Assert.NotEqual(0, blog3Id);
                }

                using (var context = new BloggingContext <TBlog>(options))
                {
                    var blogs = context.Blogs.ToList();
                    Assert.Equal(3, blogs.Count);

                    Assert.Equal("New Name", blogs.Single(b => b.Id == blog1Id).Name);

                    var blog2 = blogs.Single(b => b.Id == blog2Id);
                    Assert.Null(blog2.Name);
                    Assert.Equal(blog2.NotFigTime, new DateTime());
                    Assert.Null(blog2.AndChew);

                    var blog3 = blogs.Single(b => b.Id == blog3Id);
                    Assert.Null(blog3.Name);
                    Assert.Equal(blog3.NotFigTime, new DateTime());
                    Assert.Null(blog3.AndChew);
                }
            }
        }
Пример #19
0
        public async Task Can_save_changes()
        {
            using (var testDatabase = await SqlServerTestDatabase.Scratch())
            {
                var options = new DbContextOptions().UseSqlServer(testDatabase.Connection.ConnectionString);

                using (var db = new BloggingContext(options))
                {
                    await CreateBlogDatabaseAsync <Blog>(db);
                }

                using (var db = new BloggingContext(options))
                {
                    var toUpdate = db.Blogs.Single(b => b.Name == "Blog1");
                    toUpdate.Name = "Blog is Updated";
                    var updatedId = toUpdate.Id;
                    var toDelete  = db.Blogs.Single(b => b.Name == "Blog2");
                    toDelete.Name = "Blog to delete";
                    var deletedId = toDelete.Id;

                    db.ChangeTracker.Entry(toUpdate).State = EntityState.Modified;
                    db.ChangeTracker.Entry(toDelete).State = EntityState.Deleted;

                    var toAdd = db.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]
                    });

                    await db.SaveChangesAsync();

                    Assert.NotEqual(0, toAdd.Id);

                    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));

                    var rows = await testDatabase.ExecuteScalarAsync <int>(
                        string.Format(@"SELECT Count(*) FROM [dbo].[Blog] WHERE Id = {0} AND Name = 'Blog is Updated'", updatedId),
                        CancellationToken.None);

                    Assert.Equal(1, rows);

                    rows = await testDatabase.ExecuteScalarAsync <int>(
                        string.Format(@"SELECT Count(*) FROM [dbo].[Blog] WHERE Id = {0}", deletedId),
                        CancellationToken.None);

                    Assert.Equal(0, rows);

                    rows = await testDatabase.ExecuteScalarAsync <int>(
                        @"SELECT Count(*) FROM [dbo].[Blog] WHERE Id = 3 AND Name = 'Blog to Insert'",
                        CancellationToken.None);

                    Assert.Equal(1, rows);
                }
            }
        }