Esempio n. 1
0
            public async Task Can_query_with_explicit_services_and_OnConfiguring()
            {
                using (await TestDatabase.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());
                    }
                }
            }
Esempio n. 2
0
            public async Task Can_query_with_implicit_services_and_explicit_config()
            {
                using (await TestDatabase.Northwind())
                {
                    var configuration = new DbContextOptions()
                                        .UseSqlServer(TestDatabase.NorthwindConnectionString)
                                        .BuildConfiguration();

                    using (var context = new NorthwindContext(configuration))
                    {
                        Assert.Equal(91, await context.Customers.CountAsync());
                    }
                }
            }
Esempio n. 3
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 TestDatabase.Northwind())
                {
                    await serviceProvider.GetService <MyController>().TestAsync();
                }
            }
Esempio n. 4
0
 public async Task Throws_on_attempt_to_use_context_with_no_store()
 {
     using (await TestDatabase.Northwind())
     {
         Assert.Equal(
             GetString("FormatNoDataStoreConfigured"),
             Assert.Throws <InvalidOperationException>(() =>
         {
             using (var context = new NorthwindContext())
             {
                 Assert.Equal(91, context.Customers.Count());
             }
         }).Message);
     }
 }
Esempio n. 5
0
        public NorthwindQueryFixture()
        {
            _serviceProvider
                = new ServiceCollection()
                  .AddEntityFramework()
                  .AddSqlServer()
                  .UseLoggerFactory(_loggingFactory)
                  .ServiceCollection
                  .BuildServiceProvider();

            _testDatabase = TestDatabase.Northwind().Result;

            _options
                = new DbContextOptions()
                  .UseModel(CreateModel())
                  .UseSqlServer(_testDatabase.Connection.ConnectionString);
        }
Esempio n. 6
0
            public async Task Can_register_configuration_with_DI_container_and_have_it_injected()
            {
                var options = new DbContextOptions().UseSqlServer(TestDatabase.NorthwindConnectionString);

                var serviceCollection = new ServiceCollection();

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

                using (await TestDatabase.Northwind())
                {
                    await serviceProvider.GetService <MyController>().TestAsync();
                }
            }
Esempio n. 7
0
        public async Task Can_enumerate_entity_set()
        {
            using (await TestDatabase.Northwind())
            {
                using (var db = new NorthwindContext())
                {
                    var results = new List <Customer>();
                    foreach (var item in db.Customers)
                    {
                        results.Add(item);
                    }

                    Assert.Equal(91, results.Count);
                    Assert.Equal("ALFKI", results[0].CustomerID);
                    Assert.Equal("Alfreds Futterkiste", results[0].CompanyName);
                }
            }
        }
Esempio n. 8
0
            public async Task Throws_on_attempt_to_use_store_with_no_store_services()
            {
                using (await TestDatabase.Northwind())
                {
                    var serviceCollection = new ServiceCollection();
                    serviceCollection.AddEntityFramework();
                    var serviceProvider = serviceCollection.BuildServiceProvider();

                    Assert.Equal(
                        GetString("FormatNoDataStoreService"),
                        Assert.Throws <InvalidOperationException>(() =>
                    {
                        using (var context = new NorthwindContext(serviceProvider))
                        {
                            Assert.Equal(91, context.Customers.Count());
                        }
                    }).Message);
                }
            }
Esempio n. 9
0
        private static async Task CreateTables_creates_schema_in_existing_database_test(bool async)
        {
            using (var testDatabase = await TestDatabase.Scratch())
            {
                var serviceCollection = new ServiceCollection();
                serviceCollection.AddEntityFramework().AddSqlServer();
                var serviceProvider = serviceCollection.BuildServiceProvider();

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

                using (var context = new BloggingContext(serviceProvider, configuration))
                {
                    var creator = 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"));
                }
            }
        }
        public async Task Can_get_next_values()
        {
            using (var testDatabase = await TestDatabase.Default())
            {
                var sequenceIdentityGenerator
                    = new SequenceIdentityGenerator(testDatabase);

                var generator = new SqlServerMigrationOperationSqlGenerator(new SqlServerTypeMapper());

                await testDatabase.ExecuteNonQueryAsync(
                    generator.Generate(new[] { sequenceIdentityGenerator.CreateMigrationOperation() }, generateIdempotentSql : true).Single().Sql);

                var next = sequenceIdentityGenerator.NextAsync().Result;

                for (var i = 1; i <= 100; i++)
                {
                    Assert.Equal(next + i, await sequenceIdentityGenerator.NextAsync());
                }
            }
        }
        private static async Task EnsuredCreated_is_noop_when_database_exists_and_has_schema_test(bool async)
        {
            using (var testDatabase = await TestDatabase.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, ((RelationalConnection)context.Database.Connection).DbConnection.State);
                }
            }
        }
Esempio n. 12
0
        private static async Task Delete_will_delete_database_test(bool async)
        {
            using (var testDatabase = await TestDatabase.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());
            }
        }
Esempio n. 13
0
        public async Task Can_get_next_values()
        {
            var sequentialGuidIdentityGenerator = new SequentialGuidIdentityGenerator();
            var values = new List <Guid>();

            for (var _ = 0; _ < 100; _++)
            {
                values.Add(await sequentialGuidIdentityGenerator.NextAsync());
            }

            using (var testDatabase = await TestDatabase.Default())
            {
                await testDatabase.ExecuteNonQueryAsync("CREATE TABLE SequentialGuidTest (value uniqueidentifier)");

                for (var i = values.Count - 1; i >= 0; i--)
                {
                    await testDatabase.ExecuteNonQueryAsync("INSERT SequentialGuidTest VALUES (@p0)", values[i]);
                }

                Assert.Equal(
                    values,
                    await testDatabase.QueryAsync <Guid>("SELECT value FROM SequentialGuidTest ORDER BY value"));
            }
        }
Esempio n. 14
0
        public async Task Can_run_linq_query_on_entity_set()
        {
            using (await TestDatabase.Northwind())
            {
                using (var db = new NorthwindContext())
                {
                    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);
                }
            }
        }
Esempio n. 15
0
            private async Task NestedContextTest(Func <BlogContext> createBlogContext, Func <NorthwindContext> createNorthwindContext)
            {
                using (await TestDatabase.Northwind())
                {
                    using (var context0 = createBlogContext())
                    {
                        Assert.Equal(0, context0.ChangeTracker.Entries().Count());
                        var blog0 = context0.Add(new Blog {
                            Id = 1, Name = "Giddyup"
                        });
                        Assert.Same(blog0, context0.ChangeTracker.Entries().Select(e => e.Entity).Single());
                        await context0.SaveChangesAsync();

                        using (var context1 = createNorthwindContext())
                        {
                            var customers1 = await context1.Customers.ToListAsync();

                            Assert.Equal(91, customers1.Count);
                            Assert.Equal(91, context1.ChangeTracker.Entries().Count());
                            Assert.Same(blog0, context0.ChangeTracker.Entries().Select(e => e.Entity).Single());

                            using (var context2 = createBlogContext())
                            {
                                Assert.Equal(0, context2.ChangeTracker.Entries().Count());
                                Assert.Same(blog0, context0.ChangeTracker.Entries().Select(e => e.Entity).Single());

                                var blog0Prime = (await context2.Blogs.ToArrayAsync()).Single();
                                Assert.Same(blog0Prime, context2.ChangeTracker.Entries().Select(e => e.Entity).Single());

                                Assert.Equal(blog0.Id, blog0Prime.Id);
                                Assert.NotSame(blog0, blog0Prime);
                            }
                        }
                    }
                }
            }
Esempio n. 16
0
        private async Task RoundTripChanges <TBlog>() where TBlog : class, IBlog, new()
        {
            using (var testDatabase = await TestDatabase.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 CreateBlogDatabase <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);
                }
            }
        }
Esempio n. 17
0
        public async Task Can_save_changes()
        {
            using (var testDatabase = await TestDatabase.Scratch())
            {
                var options = new DbContextOptions().UseSqlServer(testDatabase.Connection.ConnectionString);

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

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

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

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

                    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>(
                        @"SELECT Count(*) FROM [dbo].[Blog] WHERE Id = 1 AND Name = 'Blog is Updated'",
                        CancellationToken.None);

                    Assert.Equal(1, rows);

                    rows = await testDatabase.ExecuteScalarAsync <int>(
                        @"SELECT Count(*) FROM [dbo].[Blog] WHERE Id = 2",
                        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);
                }
            }
        }
Esempio n. 18
0
 private static SqlServerDataStoreCreator GetDataStoreCreator(TestDatabase testDatabase)
 {
     return(CreateConfiguration(testDatabase).Services.ServiceProvider.GetService <SqlServerDataStoreCreator>());
 }
 public BloggingContext(TestDatabase testDatabase)
     : base(CreateServiceProvider())
 {
     _testDatabase = testDatabase;
 }
Esempio n. 20
0
 protected override void OnConfiguring(DbContextOptions options)
 {
     options.UseSqlServer(TestDatabase.CreateConnectionString(_databaseName));
 }