【问题标题】:Entity Framework Seed method is not being called实体框架种子方法没有被调用
【发布时间】:2013-12-13 06:36:36
【问题描述】:

我们正在使用 Entity Framework 4.4 并使用迁移。数据库已经存在,我们需要定期更新它。但是,没有调用种子方法,因此没有添加查找值。

代码如下:

internal sealed class Configuration : DbMigrationsConfiguration<MyDbContext>
{
        public Configuration()
        {
            AutomaticMigrationsEnabled = false;
            SetSqlGenerator("System.Data.SqlClient", new OurSqlServerMigrationSqlGenerator());
        }

        protected override void Seed(KinectionDbContext context)
        {
            SeedLookupTables(context);
        }

        private static void SeedLookupTables(KinectionDbContext context)
        {
            context.Titles.AddOrUpdate(t => t.Value,
                new Title {Value = "Mr"},
                new Title {Value = "Mrs"},
                new Title {Value = "Miss"},
                new Title {Value = "Ms"},
                new Title {Value = "Dr"}
            );

            context.SaveChanges();
        }

}


public class MyDbContext : ObjectContext
    {
        public MyDbContext()
        {

        }

        static MyDbContext ()
        {
            Database.SetInitializer<KinectionDbContext>(null);
        }

        public DbSet<Title> Titles { get; set; }

}

我们正在调用:

Add-Migration Seed

但是迁移是空的。

有谁知道为什么调用种子是 cmot 以及为什么没有检测到查找表中的附加值?

谢谢 否

【问题讨论】:

    标签: database entity-framework asp.net-mvc-4 c#-4.0 code-first


    【解决方案1】:

    迁移种子方法

    在 Update-Database PowerShell 命令运行时运行 执行

    你需要打电话给Update-Database 而不是Add-Migration

    Add-Migration 构建一个迁移文件,其中包含将数据库迁移到新版本的命令。它是空的,因为没有要进行的架构更改。如果您只想做种子,则无需在致电Update-Database 之前致电Add-Migration

    参考资料:

    Code first Db initialization strategies.
    Code first migrations recommended reading
    Managed Migrations
    Database initializer and Migrations Seed methods

    【讨论】:

    • 谢谢你,这工作:)。但是,有没有办法获取种子的sql脚本?
    • update-migration 返回一包错误,因为在我的种子方法中我使用了文件或其他逻辑实现
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-20
    • 2012-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多