如何使用 Entity Framework CodeFirst 让我的数据库播种? [英] How can I get my database to seed using Entity Framework CodeFirst?

查看:29
本文介绍了如何使用 Entity Framework CodeFirst 让我的数据库播种?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

数据库已成功创建(与表一样),但未播种.我花了几个小时阅读了大量的文章,但一直没能得到它.有什么建议吗?

The database is created successfully (as are the tables) but is not seeded. I have spent several hours and read tons of articles but have not been able to get it. Any suggestions?

附带说明一下,是否可以在不引用客户端中的 DatabaseContext 的情况下调用初始化程序?

On a side note, is it possible to call the initializer without having a reference to my DatabaseContext in the client?

我已经包含了我能想到的所有相关代码.如果还有什么有用的,请告诉我.

I have included all the relevant code I could think of. If anything else would be helpful, please let me know.

我尝试过的事情:

  1. 我删除了我的连接字符串(因为无论如何它默认为 sqlexpress,只是名称改变了)
  2. 我将 DropCreateDatabaseIfModelChanges 改为 DropCreateDatabaseAlways,还是一样.

真正奇怪的是它曾经工作过,但我不知道它是如何或为什么再次坏掉的.我假设连接字符串,但谁知道呢.

The really weird thing is it worked once, but I have no idea how or why it broke again. I am assuming connection strings, but who knows.

DatabaseInitializer.cs

DatabaseInitializer.cs

public class DatabaseInitializer : DropCreateDatabaseIfModelChanges<DatabaseContext>
{
  protected override void Seed(DatabaseContext context)
  {
    // Seeding data here
    context.SaveChanges();
  }
}

DatabaseContext.cs

DatabaseContext.cs

public class DatabaseContext : DbContext
{
  protected override void OnModelCreating(DbModelBuilder mb)
  {
    // Random mapping code
  }

  public DbSet<Entity1> Entities1 { get; set; }
  public DbSet<Entity2> Entities2 { get; set; }

}

Global.asax.cs - Application_Start()

Global.asax.cs - Application_Start()

protected void Application_Start()
{
  Database.SetInitializer<DatabaseContext>(new DatabaseInitializer());
  AreaRegistration.RegisterAllAreas();
  RegisterGlobalFilters(GlobalFilters.Filters);
  RegisterRoutes(RouteTable.Routes);
}

客户端 web.config

Client web.config

<connectionStrings>
  <add name="DatabaseContext" connectionString="data source=.SQLEXPRESS;Database=Database;Integrated Security=SSPI;" providerName="System.Data.SqlClient" />
</connectionStrings>

解决方案

为了文档,我在这里分享我的解决方案.浏览所有评论无论如何都会很痛苦.最后,我在不同的类中有 DatabaseInitializer 和 DatabaseContext.虽然这些微小的变化修复了它,但我真的不明白,但就是这样.

SOLUTION

For the sake of documentation, I am sharing my solution here. Navigating all the comments would be a pain anyways. In the end I had DatabaseInitializer and DatabaseContext in separate classes. I don't really understand while these tiny changes fixed it, but here it is.

DatabaseInitializer.cs

DatabaseInitializer.cs

public class DatabaseInitializer : CreateDatabaseIfNotExists<DatabaseContext>
{
  protected override void Seed(DatabaseContext context)
  {
    // Seed code here
  }
}

DatabaseContext.cs

DatabaseContext.cs

public class DatabaseContext : DbContext
{
  public DatabaseContext() : base("MyDatabase") { }

  protected override void OnModelCreating(DbModelBuilder mb)
  {
    // Code here
  }

  public DbSet<Entity> Entities { get; set; }
  // Other DbSets
}

Global.asax.cs - Application_Start()

Global.asax.cs - Application_Start()

protected void Application_Start()
{
  Database.SetInitializer(new DatabaseInitializer());
  AreaRegistration.RegisterAllAreas();
  RegisterGlobalFilters(GlobalFilters.Filters);
  RegisterRoutes(RouteTable.Routes);
}

推荐答案

这就是我的 DbContext 类的所有外观,它们的种子很好:

This is what my DbContext classes all look like and they seed just fine:

public class MyDbContext : DbContext
{
    public DbSet<MyClass> MyClasses { get; set; }

    protected override void OnModelCreating (DbModelBuilder modelBuilder)
    {
        base.OnModelCreating (modelBuilder);
        modelBuilder.Conventions.Remove<System.Data.Entity.ModelConfiguration.Conventions.PluralizingTableNameConvention> ();

        // Add any configuration or mapping stuff here
    }

    public void Seed (MyDbContext Context)
    {
        #if DEBUG
        // Create my debug (testing) objects here
        var TestMyClass = new MyClass () { ... };
        Context.MyClasses.Add (TestMyClass);
        #endif

        // Normal seeding goes here

        Context.SaveChanges ();
    }

    public class DropCreateIfChangeInitializer : DropCreateDatabaseIfModelChanges<MyDbContext>
    {
        protected override void Seed (MyDbContext context)
        {
            context.Seed (context);

            base.Seed (context);
        }
    }

    public class CreateInitializer : CreateDatabaseIfNotExists<MyDbContext>
    {
        protected override void Seed (MyDbContext context)
        {
            context.Seed (context);

            base.Seed (context);
        }
    }

    static MyDbContext ()
    {
        #if DEBUG
        Database.SetInitializer<MyDbContext> (new DropCreateIfChangeInitializer ());
        #else
        Database.SetInitializer<MyDbContext> (new CreateInitializer ());
        #endif
    }
}

我已经使用过这种模式几次,对我来说效果很好.

I have used this pattern a few times and it has worked out very well for me.

这篇关于如何使用 Entity Framework CodeFirst 让我的数据库播种?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆