我怎样才能让我的数据库使用实体框架codeFirst种子? [英] How can I get my database to seed using Entity Framework CodeFirst?

查看:217
本文介绍了我怎样才能让我的数据库使用实体框架codeFirst种子?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

数据库创建成功(因为是表),但没有种子。我花了几个小时,阅读吨的文章,但一直没能得到它。有什么建议?

在一个侧面说明,它是可以调用初始化而无需在客户端不必我DatabaseContext参考?

我已经包括所有相关的code我能想到的。如果什么都将是有益的,请让我知道。

事情我已经试过:


  1. 我删除了我的连接字符串(因为它默认为反正sqlex preSS,只是名字改了)

  2. 我改变DropCreateDatabaseIfModelChanges到DropCreateDatabaseAlways,还是一样。

编辑:真是奇怪的是它的工作一次,但我不知道它再如何或为何爆发。我假设的连接字符串,但谁知道。

DatabaseInitializer.cs

 公共类DatabaseInitializer:DropCreateDatabaseIfModelChanges< D​​atabaseContext>
{
  保护覆盖无效的种子(DatabaseContext上下文)
  {
    //此处播种数据
    context.SaveChanges();
  }
}

DatabaseContext.cs

 公共类DatabaseContext:的DbContext
{
  保护覆盖无效OnModelCreating(DbModelBuilder MB)
  {
    //随机映射code
  }  公共DbSet<&ENTITY1 GT;实体1 {搞定;组; }
  公共DbSet<&ENTITY2 GT; Entities2 {搞定;组; }}

的Global.asax.cs - 的Application_Start()

 保护无效的Application_Start()
{
  Database.SetInitializer&所述; DatabaseContext>(新DatabaseInitializer());
  AreaRegistration.RegisterAllAreas();
  RegisterGlobalFilters(GlobalFilters.Filters);
  的RegisterRoutes(RouteTable.Routes);
}

客户端的web.config

 <&是connectionStrings GT;
  <添加名称=DatabaseContext的connectionString =数据源= \\ SQLEX $ P $干燥综合征;数据库=数据库;集成安全性= SSPI;的providerName =System.Data.SqlClient的/>
< /&是connectionStrings GT;

SOLUTION

有关文档的缘故,我在这里分享我的解决方案。浏览所有的意见将是一个反正痛苦。最后我不得不DatabaseInitializer和DatabaseContext在不同的班级。我真的不明白,而这些微小的变化固定的,但在这里。

DatabaseInitializer.cs

 公共类DatabaseInitializer:CreateDatabaseIfNotExists< D​​atabaseContext>
{
  保护覆盖无效的种子(DatabaseContext上下文)
  {
    //种子code在这里
  }
}

DatabaseContext.cs

 公共类DatabaseContext:的DbContext
{
  公共DatabaseContext():基地(MyDatabase的){}  保护覆盖无效OnModelCreating(DbModelBuilder MB)
  {
    // code在这里
  }  公共DbSet<实体GT;实体{搞定;组; }
  //其他DbSets
}

的Global.asax.cs - 的Application_Start()

 保护无效的Application_Start()
{
  Database.SetInitializer(新DatabaseInitializer());
  AreaRegistration.RegisterAllAreas();
  RegisterGlobalFilters(GlobalFilters.Filters);
  的RegisterRoutes(RouteTable.Routes);
}


解决方案

这是我的DbContext类看起来都像他们种子就好了:

 公共类MyDbContext:的DbContext
{
    公共DbSet< MyClass的> MyClasses {搞定;组; }    保护覆盖无效OnModelCreating(DbModelBuilder模型构建器)
    {
        base.OnModelCreating(模型构建器);
        modelBuilder.Conventions.Remove<System.Data.Entity.ModelConfiguration.Conventions.PluralizingTableNameConvention> ();        //此处添加任何配置或映射的东西
    }    公共无效种子(MyDbContext上下文)
    {
        #如果DEBUG
        //创建我的调试(测试)这里对象
        VAR TestMyClass =新MyClass的(){...};
        Context.MyClasses.Add(TestMyClass);
        #万一        //正常播种到这里        Context.SaveChanges();
    }    公共类DropCreateIfChangeInitializer:DropCreateDatabaseIfModelChanges&LT; MyDbContext&GT;
    {
        保护覆盖无效的种子(MyDbContext上下文)
        {
            context.Seed(上下文);            base.Seed(上下文);
        }
    }    公共类CreateInitializer:CreateDatabaseIfNotExists&LT; MyDbContext&GT;
    {
        保护覆盖无效的种子(MyDbContext上下文)
        {
            context.Seed(上下文);            base.Seed(上下文);
        }
    }    静态MyDbContext()
    {
        #如果DEBUG
        Database.SetInitializer&LT; MyDbContext&GT; (新DropCreateIfChangeInitializer());
        #其他
        Database.SetInitializer&LT; MyDbContext&GT; (新CreateInitializer());
        #万一
    }
}

我已经使用这个模式的几十倍,并已制定了对我非常好。

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?

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.

Things I've Tried:

  1. I deleted my connection string (since it defaults to sqlexpress anyways, just the name changed)
  2. I changed DropCreateDatabaseIfModelChanges to DropCreateDatabaseAlways, still the same.

Edit: 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

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

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()

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

Client web.config

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

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

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

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()

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

解决方案

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.

这篇关于我怎样才能让我的数据库使用实体框架codeFirst种子?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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