【问题标题】:Entity Framework seed not being called实体框架种子未被调用
【发布时间】:2016-05-11 13:39:30
【问题描述】:

我在使用数据库初始化程序时遇到问题 - 从未调用过种子方法。类似的代码在另一个项目中工作,所以我很困惑为什么他们这次不工作。

这是我的代码:

RecipeContext.cs

    public class RecipeContext : DbContext
    {
      public RecipeContext() : base("DefaultConnection")
      {
      }

      public DbSet<Recipe> Recipes { get; set; }

      protected override void OnModelCreating(DbModelBuilder modelBuilder)
      {
          modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
          base.OnModelCreating(modelBuilder);
      }

      public static RecipeContext Create()
      {
          return new RecipeContext();
      }
    }

RecipeInitialiser.cs

    public class RecipeInitialiser : DropCreateDatabaseAlways<RecipeContext>
    {
      protected override void Seed(RecipeContext context)
      {
        var recipes = new List<Recipe>
        {
            new Recipe {
                Name = "Spag Bol",
                Ingredients = "1. This\n2. That\n3. This too",
                Method = "1. Do this\n2. Do that\n3. And this too",
                PrepTime = new TimeSpan(0, 45, 0),
                CookTime = new TimeSpan(1, 45, 0),
                Difficulty = 1,
                Serves = 6,
                DateCreated = DateTime.Now
            },
          };

          recipes.ForEach(r => context.Recipes.Add(r));
          context.SaveChanges();
          base.Seed(context);
    }
}

Web.config

<entityFramework>
  <contexts>
    <context type="WebRecipes.DataLayer.RecipeContext, WebRecipes.DataLayer">
      <databaseInitializer type="WebRecipes.DataLayer.Models.RecipeInitializer, WebRecipes.DataLayer" />
    </context>
  </contexts>
  ...other_settings
</entityframework>

为什么这篇文章与可能的重复文章不同:

  • 正如 Leandro Gabriel Casas 所指出的,我的 Web.config 文件中确实有错字

我尝试过的

  • 在种子方法处设置断点,显示种子方法永远不会被调用
  • 我已尝试查看 Stack Overflow here 和 here,但我无法看到哪里出错了

【问题讨论】:

  • 如何/何时运行初始化程序?您可以等待第一次使用上下文来触发初始化程序,也可以在 Application_Start() 方法中手动执行。
  • @NRKirby 是我大声笑但删除了它...因为我不确定该配置如何工作...
  • 很抱歉这么晚才添加评论,但如果您将答案标记为正确,这将有所帮助,毕竟,您在主帖中说,您在网络配置文件中有错字。

标签: c# entity-framework


【解决方案1】:

看来你打错字了。

你的初始化类名是

RecipeInitialiser

在配置中你有

&lt;databaseInitializer type="WebRecipes.DataLayer.Models.RecipeInitializer, WebRecipes.DataLayer" /&gt;

【讨论】:

    猜你喜欢
    • 2013-12-13
    • 1970-01-01
    • 1970-01-01
    • 2015-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-08
    相关资源
    最近更新 更多