DropCrateDatabase没有调用Seed方法

时间:2017-09-18 12:39:39

标签: asp.net-mvc entity-framework ef-code-first entity-framework-6

我首先尝试使用实体框架代码。 现在我想用示例数据填充我的数据库。 这是我的SampleDataClass:

public class SampleData:DropCreateDatabaseAlways<MyContext>
{
    protected override void Seed(MyContext context)
    {
        var products = new List<Product>
        {
            new Product{Name="prod1"},
            new Product{Name="prod2"}
        };

        products.ForEach(i => context.Products.Add(i));
    }
}

MyContext类:

public class MyContext:DbContext
{
    public MyContext():base("MyCon")
    {
        this.Configuration.LazyLoadingEnabled = true;
    }

    public DbSet<Product> Products { get; set; }
}

Conection string class:

  <connectionStrings>
    <add name="MyCon" connectionString="Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=DatabaseName;Integrated Security=True;" providerName="System.Data.SqlClient" />
  </connectionStrings>

我在Application_Start方法中设置了初始化程序:

    protected void Application_Start()
    {
        Database.SetInitializer(new Models.SampleData());

        AreaRegistration.RegisterAllAreas();
        RouteConfig.RegisterRoutes(RouteTable.Routes);
    }

但没有任何事情发生。 问题是什么?

1 个答案:

答案 0 :(得分:1)

注意

以下代码将指示EF在认为必要时删除并重新创建数据库。这是非常具有破坏性的!您应该更改DropCreateDatabaseIfModelChanges值以及配置初始化以防止这种情况(以下两行是配置初始化)

AutomaticMigrationsEnabled = true;
AutomaticMigrationDataLossAllowed = true;

结束注释

在您的Application_start()中,您应该拨打此类内容

Database.SetInitializer(new DropCreateDatabaseIfModelChanges<MyContext>());

using (var context = new MyContext())
{
    new MigrateDatabaseToLatestVersion<MyContext, Configuration>().InitializeDatabase(context);
}

Configuration是在Migrations\Configuration.cs中声明的类,其定义如

internal sealed class Configuration : DbMigrationsConfiguration<Context>
{
    public Configuration()
    {
        AutomaticMigrationsEnabled = true;
        AutomaticMigrationDataLossAllowed = true;
    }

    protected override void Seed(FoyerRural.Models.Contexts.Context context)
    {
     // Database code
    }
}

可以生成Configuration.cs文件。为此,您可以this tutorial

TLDR; Tools --> NuGet Package Manager --> Package Manager Console并执行Enable-Migrations