正在创建但未播种的数据库

时间:2018-04-12 12:58:30

标签: c# asp.net .net

正在创建我的本地数据库,但数据没有实现(这里的所有数据都没有意义或价值)

有人知道为什么吗?或者如何解决它。

数据库初始化程序:

public static class DbInitializer
{
    public static void Initialize(FranchiseContext context)
    {
        context.Database.EnsureCreated();

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

        //MENU
        var imgMenu = new Menu[]
        {
            new Menu { ID = 0, Path = "~/images/menu_hamburger.jpg" },
            new Menu { ID = 1, Path = "~/images/menu_hamburger.jpg" },
            // etc
        };

        foreach (Menu m in imgMenu)
        {
            context.menus.Add(m);
        }
        context.SaveChanges();
    }
}
//a lot of code being skipped but doing the same

背景信息:

public class FranchiseContext : DbContext
{
    public FranchiseContext(DbContextOptions<FranchiseContext> options) : base(options)
    {
    }

    public DbSet<Menu> menus { get; set; }
    public DbSet<Locaties> locaties { get; set; }
    public DbSet<Franchise> franchise { get; set; }
    public DbSet<Jobs> jobs { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Menu>().ToTable("Menu");
        modelBuilder.Entity<Locaties>().ToTable("Locaties");
        modelBuilder.Entity<Franchise>().ToTable("Franchise");
        modelBuilder.Entity<Jobs>().ToTable("Jobs");
    }
}

在Program.cs中我初始化数据库

    public static void Main(string[] args)
    {
        var host = BuildWebHost(args);

        using (var scope = host.Services.CreateScope())
        {
            var services = scope.ServiceProvider;
            try
            {
                var context = services.GetRequiredService<FranchiseContext>();
                DbInitializer.Initialize(context);
            }
            catch (Exception ex)
            {
                var logger = services.GetRequiredService<ILogger<Program>>();
                logger.LogError(ex, "An error occurred while seeding the database.");
            }
        }

        host.Run();
    }

我的appsettings.json

appsettings.json
{
  "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=Stage
Trusted_Connection=True;MultipleActiveResultSets=true"
  },
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Warning"
    }
  }
}

提前致谢。

0 个答案:

没有答案