简体   繁体   中英

Issues with seeding database upon first running an application using EF6 Code First

I recently upgraded to Entity Framework 6 and it seems to have broken the seeding of the database.

DataContext.cs

public class DataContext : DbContext
{
     public DbSet<BlogSettings> BlogSettings { get; set; } 
}

DataContextInitializer.cs

public class DataContextInitializer : CreateDatabaseIfNotExists<DataContext>
{
    protected override void Seed(DataContext context)
    {
        var blogSettings = new BlogSettings()
        {
            BlogTitle = "My Blog",
            MaxBlogsOnHomepageBeforeLoad = 20
        };

        context.BlogSettings.Add(blogSettings);
        context.SaveChanges();
    }
}

Note: there are more database sets and code for the seed, but it all looks exactly like this and was working with the previous version.

I created by database in MS SQL Server and created a user. I added the connection string. I then go to run the web application which should cause the tables to be generated, however I get this:

Migrations is enabled for context 'DataContext' but the database does not exist or contains no mapped tables. Use Migrations to create the database and its tables, for example by running the 'Update-Database' command from the Package Manager Console.

I have migrations set to false in Configuration.cs and I have no _MigrationHistory table.

Constructor for Configuration.cs

public Configuration()
{
    AutomaticMigrationsEnabled = false;
}

I have this in my web.config which should kick of initialization: <add key="DatabaseInitializerForType DataContext, Test" value="DataContextInitializer, Test" />

I have tried adding it in <entityFramework> under <contexts> and I have also tried initializing it in Global.asax.cs to no avail.

Database.SetInitializer(new DataContextInitializer());
using (var context = new DataContext())
{
    context.Database.Initialize(true);
}

最近,我们通过AssemblyInfo.cs添加了一个在所有其他类之前运行的类,该类在初始化程序有机会运行之前进行调用。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM