简体   繁体   English

首次使用EF6 Code First运行应用程序时播种数据库的问题

[英]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. 我最近升级到Entity Framework 6,它似乎破坏了数据库的种子。

DataContext.cs DataContext.cs

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

DataContextInitializer.cs 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. 我通过MS SQL Server中的数据库创建并创建了一个用户。 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: 然后,我去运行Web应用程序,这将导致生成表,但是我得到了:

Migrations is enabled for context 'DataContext' but the database does not exist or contains no mapped tables. 已为上下文“ DataContext”启用了迁移,但是数据库不存在或不包含映射表。 Use Migrations to create the database and its tables, for example by running the 'Update-Database' command from the Package Manager Console. 使用迁移来创建数据库及其表,例如,通过从程序包管理器控制台中运行“ Update-Database”命令。

I have migrations set to false in Configuration.cs and I have no _MigrationHistory table. 我在Configuration.cs _MigrationHistory迁移设置为false,并且没有_MigrationHistory表。

Constructor for Configuration.cs 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" /> 我在web.config文件中对此进行了初始化: <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. 我曾尝试将其添加在<entityFramework><contexts>和我还试图在初始化它Global.asax.cs无济于事。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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