【问题标题】:Seeding not working in Entity Framework Code First Approach在实体框架代码优先方法中播种不起作用
【发布时间】:2016-11-08 00:51:23
【问题描述】:

我正在开发一个 .Net 项目。我正在使用实体框架代码优先方法与数据库进行交互。我在开发过程中将一些模拟数据播种到我的数据库中。但是播种不起作用。我点击了这个链接 - http://www.entityframeworktutorial.net/code-first/seed-database-in-code-first.aspx。

这是我的 ContextInitializer 类

public class ContextInitializer : System.Data.Entity.CreateDatabaseIfNotExists<StoreContext>
    {

        protected override void Seed(StoreContext context)
        {
            IList<Brand> brands = new List<Brand>();
            brands.Add(new Brand { Name = "Giordano" ,TotalSale = 1 });
            brands.Add(new Brand { Name = "Nike" , TotalSale = 3 });

            foreach(Brand brand in brands)
            {
                context.Brands.Add(brand);
            }
            base.Seed(context);
            context.SaveChanges();

        }
    }

这是我的上下文类

public class StoreContext : DbContext,IDisposable
    {
        public StoreContext():base("DefaultConnection")
        {
            Database.SetInitializer(new ContextInitializer());
        }

        public virtual DbSet<Category> Categories { get; set; }
        public virtual DbSet<Brand> Brands { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
        }
   }

这是我的品牌类

public class Brand
    {
        public int Id { get; set; }
        [Required]
        [MaxLength(40)]
        public string Name { get; set; }
        public int TotalSale { get; set; }
    }

我在网上搜索了解决方案并按照说明进行操作。我也运行 context.SaveChanges。但它不是将数据播种到数据库。为什么它不起作用?

【问题讨论】:

    标签: entity-framework database-migration seeding


    【解决方案1】:

    为数据库设置初始化程序必须在在上下文被创建之前发生,所以...

        public StoreContext():base("DefaultConnection")
        {
            Database.SetInitializer(new ContextInitializer());
        }
    

    为时已晚。如果您将其设为静态,则它可以工作:

        static StoreContext()
        {
            Database.SetInitializer(new ContextInitializer());
        }
    

    【讨论】:

    • 我添加了这个静态 StoreContext() { Database.SetInitializer(new ContextInitializer()); } 下面现有的构造函数。但它不起作用。我无法删除现有的构造函数,因为它定义了连接字符串,如果我这样做会抛出错误。请问我在做什么有什么问题吗?
    • 哦。我想我需要添加这个 到 web.config 文件。但是当我添加时,它说无法设置初始化程序。我设置 PatheinFashionStore.Domain.Concrete.StoreContext 是我的上下文类和 PatheinFashionStore 主项目。所以请问这是正确的。我设置的方式。
    • 创建数据库时调用数据库初始化程序上的 Seed() 方法,它不处理现有数据(来自 DbMigrationsConfiguration 的种子处理它们,检查指定实体是否存在)。
    【解决方案2】:

    如果您删除现有数据库并且 EF 将创建并播种数据,则您的代码正在运行

    或者

    您可以使用DbMigrationsConfiguration insted of CreateDatabaseIfNotExists 并按如下方式更改您的代码:

    首先你必须删除现有的数据库

    ContextInitializer 类

    public class ContextInitializer : System.Data.Entity.Migrations.DbMigrationsConfiguration<StoreContext>
    {
        public ContextInitializer()
        {
            this.AutomaticMigrationDataLossAllowed = true;
            this.AutomaticMigrationsEnabled = true;
        }
        protected override void Seed(StoreContext context)
        {
            IList<Brand> brands = new List<Brand>();
            brands.Add(new Brand { Name = "Giordano", TotalSale = 1 });
            brands.Add(new Brand { Name = "Nike", TotalSale = 3 });
    
            foreach (Brand brand in brands)
            {
                context.Brands.AddOrUpdate(m => m.Name, brand);
            }
            base.Seed(context);
            context.SaveChanges();
    
        }
    }
    

    StoreContext

    public class StoreContext : DbContext, IDisposable
        {
            public StoreContext() : base("DefaultConnection")
            {
                Database.SetInitializer(new MigrateDatabaseToLatestVersion<StoreContext, ContextInitializer>());
                //  Database.SetInitializer(new ContextInitializer());
            }
    
            public virtual DbSet<Category> Categories { get; set; }
            public virtual DbSet<Brand> Brands { get; set; }
    
            protected override void OnModelCreating(DbModelBuilder modelBuilder)
            {
            }
        }
    

    然后种子中的任何更改都会自动反映到您的数据库中

    【讨论】:

    • 如果我从 DbMigrationsConfiguration 继承,它会在编译期间抛出错误。
    • 尝试使用 System.Data.Entity.Migrations 添加;
    • 当我运行时,它会抛出异常“无法更新与当前模型匹配的数据库”。当我从控制台更新数据库时,它说“在程序集'PatheinFashionStore.Domain'中找到了多个迁移配置类型。指定要使用的名称。”。我正在使用第二种方式。
    【解决方案3】:

    您使用了错误的初始化程序,只有在数据库不存在时才会调用 CreateDatabaseIfNotExists!

    您可以使用例如 DropCreateDatabaseIfModelChanges:

    解决方案 1)

    public class ContextInitializer : System.Data.Entity.DropCreateDatabaseIfModelChanges<StoreContext>
    {
    

    您必须小心这种方法,它!!!删除!!!所有现有数据。

    解决方案 2)

    创建自定义 DbMigrationsConfiguration:

    public class Configuration : DbMigrationsConfiguration<StoreContext>
    {
        public Configuration()
        {
            // Take here! read about this property!
            this.AutomaticMigrationDataLossAllowed = true;
            this.AutomaticMigrationsEnabled = false;
        }
    
        protected override void Seed(StoreContext context)
        {
            IList<Brand> brands = new List<Brand>();
            brands.Add(new Brand { Name = "Giordano", TotalSale = 1 });
            brands.Add(new Brand { Name = "Nike", TotalSale = 3 });
    
            foreach (Brand brand in brands)
            {
                context.Brands.AddOrUpdate(m => m.Name, brand);
            }
            base.Seed(context);
            context.SaveChanges();
        }
    }
    

    这样就可以调用(!!在创建DbContext之前或者在DbContext构造函数中!!):

    // You can put me also in DbContext constuctor     
    Database.SetInitializer(new MigrateDatabaseToLatestVersion<StoreContext , Yournamespace.Migrations.Configuration>("DefaultConnection"));
    

    注意事项:

    • DbMigrationsConfiguration 需要了解连接字符串,您可以在构造函数中或从外部提供此信息。
    • 在您的 DbMigrationsConfiguration 中,您还可以配置:
      • 迁移命名空间
      • 迁移程序集
      • 迁移目录
      • 目标数据库

    如果您像我的示例一样保留所有默认设置,那么您无需更改任何内容!

    【讨论】:

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