0

I'm trying to fill the database with my StoreInitializer, but tables are empty, I'm using Entity Framework Core and ASP.NET Core, I want to configure my Initializer for using Update-Database in Package Manager Console. I followed this tutorial https://learn.microsoft.com/pl-pl/aspnet/core/data/ef-mvc/intro but on start or on updating, database is empty anyway. Visual studio shows me no errors.

StoreInitializer.cs :

namespace PC_SHOP.DAL
{
    public static class StoreInitializer
    {


        public static void Initialize(StoreContext context)
        {

            context.Database.EnsureCreated();

            if (context.Electronics.Any())
            {
                return;
            }


            // Działy główne
            var electronics = new Electronic[]
            {
                new Electronic { ID=1, Name = "Laptopy"},
                new Electronic { ID=2, Name = "Komputery"},
                new Electronic { ID=3, Name = "Części PC"},
                new Electronic { ID=4, Name = "Dla graczy"},
                new Electronic { ID=5, Name = "Peryferia PC"},
                new Electronic { ID=6, Name = "Sieci i komunikacja"},
                new Electronic { ID=7, Name = "Oprogramowanie"},

            };

            foreach (Electronic e in electronics)
            {
                context.Electronics.Add(e);
            }

            context.SaveChanges();



            // Rodzaje laptopów
            var laptops = new List<Laptop>
            {
                new Laptop { ID=1, Name = "Laptopy", ElectronicID = 1, IconFileName = "1_laptop.jpg"},
                new Laptop { ID=2, Name = "Laptopy Apple", ElectronicID = 1, IconFileName = "2_apple.jpg"},

            };

            foreach (Laptop l in laptops)
            {
                context.Laptops.Add(l);
            }

            context.SaveChanges();


        }


    }
}

StoreContext.cs :

namespace PC_SHOP.DAL
{
    public class StoreContext : DbContext
    {
        public StoreContext(DbContextOptions<StoreContext> options) : base(options)
        {

        }

        public DbSet<Electronic> Electronics { get; set; }
        public DbSet<Laptop> Laptops { get; set; }
        public DbSet<LaptopProduct> LaptopProducts { get; set; }
        public DbSet<Employee> Employee { get; set; }
        public DbSet<Project> Project { get; set; }


        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Electronic>().ToTable("Electronic");
            modelBuilder.Entity<Laptop>().ToTable("Laptop");
            modelBuilder.Entity<LaptopProduct>().ToTable("LaptopProduct");
            modelBuilder.Entity<Employee>().ToTable("Employee");
            modelBuilder.Entity<Project>().ToTable("Project");
        }



    }
}

In ConfigurationServies in Startup.cs i added:

services.AddDbContext<StoreContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

and in appsettings.json:

"ConnectionStrings": {
    "DefaultConnection": "Data Source=DESKTOP-J0OBBIO\\SQLEXPRESS;Initial Catalog=PC_SHOP;Integrated Security=SSPI;Database=Employee;Trusted_Connection=True;MultipleActiveResultSets=true"
  },  
4
  • Where are you calling DbInitializer.Initialize()? Commented Feb 25, 2018 at 20:05
  • When program starts in Program.cs with method Main (watch link in description) or via migrations with Update-database later Commented Feb 25, 2018 at 20:07
  • are you sure the method is passed and no exceptions occur? Also, which method do you use to ensure the database is empty? Commented Feb 25, 2018 at 20:44
  • I deleted it by myslef :) and is not filling the new database anyway, vs2017 shows me no error, and updating shows message: "done." Commented Feb 25, 2018 at 20:46

3 Answers 3

1

Ok i fixed that,

I added context parameter to Configure method in Startup.cs file. Everything else have not been changed.

public void Configure(IApplicationBuilder app, IHostingEnvironment env, StoreContext context )
{
    ...
    //After app.UseMvc()
    StoreInitializer.Initialize(context);
}

And it's filling my database correctly

Sign up to request clarification or add additional context in comments.

Comments

1

Add this line to Program.cs Main() method : StoreInitializer.Initialize(context);

public static void Main(string[] args)
{
      //CreateWebHostBuilder(args).Build().Run();
      var host = CreateWebHostBuilder(args).Build();
      using (var scope = host.Services.CreateScope())
      {
            var services = scope.ServiceProvider;
            try
            {
                  var context = services.GetRequiredService<AppDbContext>();
                  //context.Database.EnsureCreated();
                  DbInitializer.Initialize(context);
            }
            catch (Exception ex)
            {
                  var logger = services.GetRequiredService<ILogger<Program>>();
                  logger.LogError(ex, "An error occurred creating the DB.");
            }
      }
      host.Run();
}

1 Comment

I can recommend this way to go.
0

EnsureCreated can be used to create the database and tables in prototyping and testing scenarios. It should be used instead of, not together with Migrations. It will only create the database if it does not exist or contains no tables. In other cases it will do nothing.

Note that if the database exists it will not do anything, so you need to use a database name that does not exist.

Really you should be generating migrations from the comand line then running the migrations from your initializer instead of using .EnsureCreated. EnsureCreated is for in memory database that is created each time. ie prototyping.

5 Comments

I'm using that tutorial from msn why on thier db is working ?? And filling? I've deleted the db and no result, creating on clear db and nothing
I guess you should read the whole series to do it the right way rather than follow each tutorial step by step. I see they use the same project correctly with migrations in this tutorial of the same series learn.microsoft.com/pl-pl/aspnet/core/data/ef-mvc/migrations However it should work if the db does not exist at all it should create it and populate it. It should work for example with the in memory provider learn.microsoft.com/en-us/ef/core/providers/in-memory
So what i'm doing wrong? It creates me the tables but not filling them, and i'm doing it with pure db and no results.
Have you stepped through the code with the debugger to make sure it is adding the data from code? DbContext is usually a scoped per request service and typically you only call savechanges one time per request, so I would call it only once after adding all the data.
I've changed still nothing, only one which is adding to db is one record from Migration History, nothing else, any ideas?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.