Пример #1
0
        public async void Speed2()
        {
            using (Context context = Context.ContextDesignFactory.CreateDbContext(Config))
            {
                ILogger <ContextSeed> logger = new Microsoft.Extensions.Logging.Abstractions.NullLogger <ContextSeed>();
                ContextSeed           seed   = new ContextSeed();
                await seed.SeedAsync(context, logger, false, Environment.CurrentDirectory, "");
            }

            using (Context context = Context.ContextDesignFactory.CreateDbContext(Config))
            {
                List <Item> item = await context.Items.AsTracking()
                                   .Include(i => i.Brand)
                                   .Include(i => i.ItemCategories)
                                   .ThenInclude(t => t.Category)
                                   .Include(i => i.Variants)
                                   .ThenInclude(v => v.Vendor)
                                   .Include(i => i.Variants)
                                   .ThenInclude(v => v.Unit)
                                   .ToListAsync();

                Assert.NotNull(item[0].Brand);
                Assert.NotNull(item[0].ItemCategories[0].Category);
                Assert.NotNull(item[0].Variants[0].Unit);
                Assert.NotNull(item[0].Variants[0].Vendor);

                await context.Database.EnsureDeletedAsync();
            }
        }
Пример #2
0
        public static async Task Main(string[] args)
        {
            var host = CreateHostBuilder(args).Build();

            using (var scope = host.Services.CreateScope())
            {
                var services      = scope.ServiceProvider;
                var loggerFactory = services.GetRequiredService <ILoggerFactory>();
                try
                {
                    var context = services.GetRequiredService <LibraryContext>();
                    await context.Database.MigrateAsync();

                    await ContextSeed.SeedAsync(context, loggerFactory);

                    var userManager     = services.GetRequiredService <UserManager <AppUser> >();
                    var identityContext = services.GetRequiredService <LibraryIdentityDbContext>();
                    await identityContext.Database.MigrateAsync();

                    await LibraryIdentityDbContextSeed.SeedUserData(userManager);
                }
                catch (Exception ex)
                {
                    var logger = loggerFactory.CreateLogger <Program>();
                    logger.LogError(ex, "An error occured during migration");
                }
            }
            host.Run();
        }
Пример #3
0
        public async void Speed3()
        {
            using (Context context = Context.ContextDesignFactory.CreateDbContext(Config))
            {
                ILogger <ContextSeed> logger = new Microsoft.Extensions.Logging.Abstractions.NullLogger <ContextSeed>();
                ContextSeed           seed   = new ContextSeed();
                await seed.SeedAsync(context, logger, false, Environment.CurrentDirectory, "");
            }

            using (Context context = Context.ContextDesignFactory.CreateDbContext(Config))
            {
                List <Brand> brands = await context.Brands.AsTracking().ToListAsync();

                List <Vendor> vendors = await context.Vendors.AsTracking().ToListAsync();

                List <ROL.Services.Catalog.Domain.Unit> units = await context.Units.AsTracking().ToListAsync();

                List <Category> categories = await context.Categories.AsTracking().ToListAsync();

                List <Item> item = await context.Items.AsTracking()
                                   .Include(i => i.ItemCategories)
                                   .Include(i => i.Variants)
                                   .ToListAsync();

                Assert.NotNull(item[0].Brand);
                Assert.NotNull(item[0].ItemCategories[0].Category);
                Assert.NotNull(item[0].Variants[0].Unit);
                Assert.NotNull(item[0].Variants[0].Vendor);

                await context.Database.EnsureDeletedAsync();
            }
        }
Пример #4
0
        public async void NoTrackingTest()
        {
            using (Context context = Context.ContextDesignFactory.CreateDbContext(Config))
            {
                ILogger <ContextSeed> logger = new Microsoft.Extensions.Logging.Abstractions.NullLogger <ContextSeed>();
                ContextSeed           seed   = new ContextSeed();
                await seed.SeedAsync(context, logger, false, Environment.CurrentDirectory, "");

                Item item = await context.Items.AsTracking().Where(i => i.Name == "5-MTHF").FirstOrDefaultAsync();

                Assert.Empty(item.MetaData);
                item.Name += " - updated";

                Assert.Equal(EntityState.Modified, context.Entry(item).State);

                int changes = await context.SaveChangesAsync();

                Assert.Equal(1, changes);
                Assert.Equal(EntityState.Unchanged, context.Entry(item).State);
            }

            using (Context context2 = Context.ContextDesignFactory.CreateDbContext(Config))
            {
                Item item2 = await context2.Items.Where(i => i.Name == "5-MTHF - updated").FirstOrDefaultAsync();

                Assert.NotNull(item2);
                await context2.Database.EnsureDeletedAsync();
            }
        }
Пример #5
0
        public async void MetaDataTest()
        {
            using (Context context = Context.ContextDesignFactory.CreateDbContext(Config))
            {
                ILogger <ContextSeed> logger = new Microsoft.Extensions.Logging.Abstractions.NullLogger <ContextSeed>();
                ContextSeed           seed   = new ContextSeed();
                await seed.SeedAsync(context, logger, false, Environment.CurrentDirectory, "");
            }

            using (Context context = Context.ContextDesignFactory.CreateDbContext(Config))
            {
                List <Brand> brands = await context.Brands.AsTracking().ToListAsync();

                List <Vendor> vendors = await context.Vendors.AsTracking().ToListAsync();

                List <ROL.Services.Catalog.Domain.Unit> units = await context.Units.AsTracking().ToListAsync();

                List <Category> categories = await context.Categories.AsTracking().ToListAsync();

                Item item = await context.Items.AsTracking()
                            .Include(i => i.ItemCategories)
                            .Include(i => i.Variants)
                            .Where(i => i.Name == "5-MTHF")
                            .FirstOrDefaultAsync();

                Assert.Empty(item.MetaData);
                item.MetaData.Add("Test1", "1");
                item.MetaData.Add("Test2", "2");
                item.MetaData.Add("Test3", "3");

                Assert.True(context.Entry(item).Property(p => p.MetaData).IsModified, "Property is modified");
                Assert.Equal(EntityState.Modified, context.Entry(item).State);
                int changes = await context.SaveChangesAsync();

                Assert.Equal(EntityState.Unchanged, context.Entry(item).State);
            }

            using (Context context2 = Context.ContextDesignFactory.CreateDbContext(Config))
            {
                List <Brand> brands = await context2.Brands.AsTracking().ToListAsync();

                List <Vendor> vendors = await context2.Vendors.AsTracking().ToListAsync();

                List <ROL.Services.Catalog.Domain.Unit> units = await context2.Units.AsTracking().ToListAsync();

                List <Category> categories = await context2.Categories.AsTracking().ToListAsync();

                Item item2 = await context2.Items
                             .Include(i => i.ItemCategories)
                             .Include(i => i.Variants)
                             .Where(i => i.Name == "5-MTHF")
                             .FirstOrDefaultAsync();

                Assert.Equal("1", item2.MetaData["Test1"]);
                Assert.Equal("2", item2.MetaData["Test2"]);
                Assert.Equal("3", item2.MetaData["Test3"]);

                await context2.Database.EnsureDeletedAsync();
            }
        }
Пример #6
0
        public async void MetaDataTest2()
        {
            using (Context context = Context.ContextDesignFactory.CreateDbContext(Config))
            {
                ILogger <ContextSeed> logger = new Microsoft.Extensions.Logging.Abstractions.NullLogger <ContextSeed>();
                ContextSeed           seed   = new ContextSeed();
                await seed.SeedAsync(context, logger, false, Environment.CurrentDirectory, "");
            }

            using (Context context = Context.ContextDesignFactory.CreateDbContext(Config))
            {
                Item item = await context.Items.AsTracking()
                            .Include(i => i.Brand)
                            .Include(i => i.ItemCategories)
                            .ThenInclude(t => t.Category)
                            .Include(i => i.Variants)
                            .ThenInclude(v => v.Vendor)
                            .Include(i => i.Variants)
                            .ThenInclude(v => v.Unit)
                            .Where(i => i.Name == "5-MTHF")
                            .FirstOrDefaultAsync();

                Assert.Empty(item.MetaData);
                item.MetaData.Add("Test1", "1");
                item.MetaData.Add("Test2", "2");
                item.MetaData.Add("Test3", "3");
                Assert.Equal(EntityState.Modified, context.Entry(item).State);
                int changes = await context.SaveChangesAsync();

                Assert.Equal(1, changes);
                Assert.Equal(EntityState.Unchanged, context.Entry(item).State);
            }

            using (Context context2 = Context.ContextDesignFactory.CreateDbContext(Config))
            {
                Item item2 = await context2.Items
                             .Include(i => i.Brand)
                             .Include(i => i.ItemCategories)
                             .ThenInclude(t => t.Category)
                             .Include(i => i.Variants)
                             .ThenInclude(v => v.Vendor)
                             .Include(i => i.Variants)
                             .ThenInclude(v => v.Unit)
                             .Where(i => i.Name == "5-MTHF")
                             .FirstOrDefaultAsync();

                Assert.Equal("1", item2.MetaData["Test1"]);
                Assert.Equal("2", item2.MetaData["Test2"]);
                Assert.Equal("3", item2.MetaData["Test3"]);

                await context2.Database.EnsureDeletedAsync();
            }
        }
        protected override void ConfigureWebHost(IWebHostBuilder builder)
        {
            builder.ConfigureServices(services =>
            {
                services.AddEntityFrameworkInMemoryDatabase();

                // Create a new service provider.
                var provider = services
                               .AddEntityFrameworkInMemoryDatabase()
                               .BuildServiceProvider();

                // Add a database context (ApplicationDbContext) using an in-memory
                // database for testing.
                services.AddDbContext <Context>(options =>
                {
                    options.UseInMemoryDatabase("ecomm");
                    options.UseInternalServiceProvider(provider);
                });

                // Build the service provider.
                var sp = services.BuildServiceProvider();

                // Create a scope to obtain a reference to the database
                // context (ApplicationDbContext).
                using (var scope = sp.CreateScope())
                {
                    var scopedServices = scope.ServiceProvider;
                    var db             = scopedServices.GetRequiredService <Context>();
                    var loggerFactory  = scopedServices.GetRequiredService <ILoggerFactory>();

                    var logger = scopedServices
                                 .GetRequiredService <ILogger <CustomWebApplicationFactory <TStartup> > >();

                    // Ensure the database is created.
                    db.Database.EnsureCreated();

                    try
                    {
                        // Seed the database with test data.
                        ContextSeed.SeedAsync(db, loggerFactory).Wait();
                    }
                    catch (Exception ex)
                    {
                        logger.LogError(ex, $"An error occurred seeding the " +
                                        "database with test messages. Error: {ex.Message}");
                    }
                }
            });
        }
Пример #8
0
        public DatabaseFixture()
        {
            ServiceCollection serviceCollection = new ServiceCollection();

            ConfigureServices(serviceCollection);
            this.serviceProvider = serviceCollection.BuildServiceProvider();

            Config = new ConfigurationBuilder()
                     .SetBasePath(Directory.GetCurrentDirectory())
                     .AddJsonFile("appsettings.json", false)
                     .Build();

            Context = this.serviceProvider.GetService <Context>();            // Context.ContextDesignFactory.CreateDbContext(Config);
            ILogger <ContextSeed> logger = new Microsoft.Extensions.Logging.Abstractions.NullLogger <ContextSeed>();
            ContextSeed           seed   = new ContextSeed();

            seed.SeedAsync(Context, logger, false, Environment.CurrentDirectory, "").Wait();
        }
Пример #9
0
        /// <summary>
        /// add mock data sql memory
        /// </summary>
        /// <param name="host"></param>
        private static void SeedDatabase(IHost host)
        {
            using (var scope = host.Services.CreateScope())
            {
                var services      = scope.ServiceProvider;
                var loggerFactory = services.GetRequiredService <ILoggerFactory>();

                try
                {
                    var aspnetRunContext = services.GetRequiredService <Context>();
                    ContextSeed.SeedAsync(aspnetRunContext, loggerFactory).Wait();
                }
                catch (Exception exception)
                {
                    var logger = loggerFactory.CreateLogger <Program>();
                    logger.LogError(exception, "An error occurred seeding the DB.");
                }
            }
        }
Пример #10
0
        public async void NoTrackingTest2()
        {
            Item item  = null;
            int  count = 0;

            using (Context context = Context.ContextDesignFactory.CreateDbContext(Config))
            {
                ILogger <ContextSeed> logger = new Microsoft.Extensions.Logging.Abstractions.NullLogger <ContextSeed>();
                ContextSeed           seed   = new ContextSeed();
                await seed.SeedAsync(context, logger, false, Environment.CurrentDirectory, "");

                item = await context.Items.Where(i => i.Name == "5-MTHF").FirstOrDefaultAsync();

                item.Name += " - updated2";
                //				context.Update<Item>(item);
                int changes = await context.SaveChangesAsync();

                Assert.Equal(0, changes);
                count = context.Items.Count();
            }


            using (Context context = Context.ContextDesignFactory.CreateDbContext(Config))
            {
//				item.Name += " - updated2";
                context.Update <Item>(item);
//				context.Entry(item).State = EntityState.Modified;
//				Assert.Throws<InvalidOperationException>(() => context.Items.Update(item));
                int changes = await context.SaveChangesAsync();

                Assert.Equal(1, changes);
            }

            using (Context context2 = Context.ContextDesignFactory.CreateDbContext(Config))
            {
                Item item2 = await context2.Items.Where(i => i.Name == "5-MTHF - updated2").FirstOrDefaultAsync();

                Assert.NotNull(item2);
                Assert.Equal(count, context2.Items.Count());
                await context2.Database.EnsureDeletedAsync();
            }
        }
Пример #11
0
        public static void Main(string[] args)
        {
            var host = CreateHostBuilder(args).Build();

            using var scope = host.Services.CreateScope();
            var services = scope.ServiceProvider;

            try
            {
                var context = services.GetRequiredService <ApplicationDbContext>();
                DbInitializer.Initialize(context);
                var userManager = services.GetRequiredService <UserManager <ApplicationUser> >();
                var roleManager = services.GetRequiredService <RoleManager <ApplicationRole> >();
                var result      = Task.Run(async() => await ContextSeed.SeedAsync(userManager, roleManager));
            }
            catch (Exception ex)
            {
                var logger = services.GetRequiredService <ILogger <Program> >();
                logger.LogError(ex, "An error occurred creating the DB.");
            }

            host.Run();
        }
Пример #12
0
        public async void MetaDataTest4()
        {
            using (Context context = Context.ContextDesignFactory.CreateDbContext(Config))
            {
                ILogger <ContextSeed> logger = new Microsoft.Extensions.Logging.Abstractions.NullLogger <ContextSeed>();
                ContextSeed           seed   = new ContextSeed();
                await seed.SeedAsync(context, logger, false, Environment.CurrentDirectory, "");
            }

            using (Context context = Context.ContextDesignFactory.CreateDbContext(Config))
            {
                Item item = await context.Items.AsTracking()
                            .Include(i => i.Brand)
                            .Include(i => i.ItemCategories)
                            .ThenInclude(t => t.Category)
                            .Include(i => i.Variants)
                            .ThenInclude(v => v.Vendor)
                            .Include(i => i.Variants)
                            .ThenInclude(v => v.Unit)
                            .Where(i => i.Name == "5-MTHF")
                            .FirstOrDefaultAsync();

                Assert.Empty(item.MetaData);
                item.MetaData.Add("Test1", "1");
                item.MetaData.Add("Test2", new List <string> {
                    "Test", "this"
                });
                item.MetaData.Add("Test3", new person {
                    FirstName = "Robert", LastName = "Raboud", MiddleName = "Alfred"
                });

                Assert.Equal(EntityState.Modified, context.Entry(item).State);
                int changes = await context.SaveChangesAsync();

                Assert.Equal(1, changes);
                Assert.Equal(EntityState.Unchanged, context.Entry(item).State);
            }

            using (Context context2 = Context.ContextDesignFactory.CreateDbContext(Config))
            {
                Item item2 = await context2.Items
                             .Include(i => i.Brand)
                             .Include(i => i.ItemCategories)
                             .ThenInclude(t => t.Category)
                             .Include(i => i.Variants)
                             .ThenInclude(v => v.Vendor)
                             .Include(i => i.Variants)
                             .ThenInclude(v => v.Unit)
                             .Where(i => i.Name == "5-MTHF")
                             .FirstOrDefaultAsync();

                Assert.Equal("1", item2.MetaData["Test1"]);

                List <string> list = item2.MetaData["Test2"] as List <string>;
                Assert.NotNull(list);
                Assert.NotEmpty(list);
                Assert.Equal("Test", list[0]);
                Assert.Equal("this", list[1]);

                person person = item2.MetaData["Test3"] as person;
                Assert.Equal("Robert", person.FirstName);
                Assert.Equal("Alfred", person.MiddleName);
                Assert.Equal("Raboud", person.LastName);

                await context2.Database.EnsureDeletedAsync();
            }
        }