实体框架初始化程序 - 种子数据库 [英] Entity Framework Initializer - seed database

查看:84
本文介绍了实体框架初始化程序 - 种子数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


我正在使用Entity Framework进行代码优先迁移。我想在创建后为我的数据库播种(我正在使用creatIfNotExist)。是否可以将迁移与继承自creatIfNotExist的初始化程序结合使用?

I'm using Entity Framework with code first migrations. I want to seed my database after creation(I'm using creatIfNotExist). Is it possible to combine migrations with initializer that inherit from creatIfNotExist?


我的代码:

my code:

static class Program
 {
   static void Main()
   {

     using (var db = new myDbContext())
     {
       db.Database.CreateIfNotExists();
     }
   }
}

  public sealed class Configuration : DbMigrationsConfiguration<Core.Models.SpanTesterContainer>
  {


    public Configuration()
    {
    AutomaticMigrationsEnabled = true;

    }

    protected override void Seed(Core.Models.SpanTesterContainer context){}
  } 


  public partial class myDbContext : DbContext
  {
    static SpanTesterContainer()
    {
      Database.SetInitializer<myDbContext>(new myDBInitializer());
    }

    public myDbContext()
    : base("Data Source=" +
           Properties.Settings.Default.ServerName + ";Initial Catalog=" +
           Properties.Settings.Default.DbName + ";Integrated Security=True;MultipleActiveResultSets=True")
    {
   }


public class SpanTesterDBInitializer : CreateDatabaseIfNotExists<SpanTesterContainer>
    {
        protected override void Seed(SpanTesterContainer context)
        {
           //Seed code here.
        }






推荐答案

Hi Barak,

Hi Barak,

>>我想在创建后播种我的数据库(我正在使用creatIfNotExist)。

>>I want to seed my database after creation(I'm using creatIfNotExist).

根据您的描述,是否要从种子初始化数据?您可以在xxDbcontext的构造函数中创建一个Initialize对象。您可以参考以下链接获取更多信息。

According to your description, do you want to Initialize the data from seed? You could create a Initialize object in you xxDbcontext’s constructor, You could refer to the following link for more information.

http://www.entityframeworktutorial.net/code-first/seed-database-in-code-first.aspx

>>
是否可以将迁移与继承自creatIfNotExist的初始化程序结合使用?

>> Is it possible to combine migrations with initializer that inherit from creatIfNotExist?

根据您的描述,我认为如果您想在迁移后初始化某些数据,是吗?如果是这样,您可以覆盖配置类上名为"seed"的方法。您可以参考下面的链接了解详细信息。

According to your description, I suppose that if you want to Initialize some data after migration, does it? If so, you could override the method named "seed" on the configuration class. And you could refer the link as below for detail.

http://www.asp.net/mvc/overview/getting-开始/开始使用-ff-using-mvc / migrations-and-deployment-with-the-entity-framework-in-an-asp-net-mvc-application

我希望它对你有所帮助。

I hope it’s helpful to you.

祝你好运,


这篇关于实体框架初始化程序 - 种子数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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