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"
},
DbInitializer.Initialize()?