简体   繁体   English

Database.SetInitializer是否不播种数据库?

[英]Database.SetInitializer is not seeding the database?

I am using enitity framework version 6.1.0 code first approch . 我正在使用enitity framework version 6.1.0 code first approch The database is just creating fine but when come to seeding part it is not seeding the override Seed Method. 数据库只是创建良好,但是当涉及到种子部分时,它并没有为覆盖种子方法提供种子。

How do i make to seed my data? 我该如何播种我的数据?

My testing implementation is as 我的测试实现是

public class Products
{
    public Products()
    {
        this.Categories = new HashSet<Categories>();
    }

    [ScaffoldColumn(false)]
    [Key()]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int ProductId { get; set; }

    [Required,StringLength(100),Display(Name="Product Name")]
    public string Name { get; set; }

    public int? CategoryId { get; set; }
    public virtual ICollection<Categories>  Categories{ get; set; }
}

public class Categories
{
    [ScaffoldColumn(false)]
    [Key()]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int CategoryId { get; set; }

    [Required,StringLength(100),Display(Name="Category")]
    public string Name { get; set; }
    public virtual ICollection<Products> Products { get; set; }

}

The ProductsInitializer is inherited from DropIfModelchanges ProductsInitializer继承自DropIfModelchanges

 public class ProductsDatabaseInitializer : DropCreateDatabaseIfModelChanges<ETestContext>
 {
    protected override void Seed(ETestContext context)
    {
        GetCategories().ForEach(c => context.Categories.Add(c));
        GetProducts().ForEach(p => context.Products.Add(p));
        context.SaveChanges();

        base.Seed(context);
    }

    private static List<Categories> GetCategories()
    {
        var categories = new List<Categories>{
            new Categories{
                CategoryId=101,
                Name="Electronics"
            },
            new Categories{
                CategoryId=102,
                Name="Clothing"
            }
        };
        return categories;
    }

    private static List<Products> GetProducts()
    {
        var products = new List<Products>{
           new Products{
             CategoryId = 101,
             ProductId=1,
             Name="Laptops"
           },
           new Products{
             CategoryId = 101,
             ProductId=2,
             Name="Desktops"
           },
           new Products{
             CategoryId = 102,
             ProductId=3,
             Name="Male Clothing"
           },
           new Products{
             CategoryId = 102,
             ProductId=4,
             Name="Female Clothing"
           }
       };
        return products;
    }


}

And My DBcontext class is as 和我的DBcontext类是

public class ETestContext : DbContext
{

    public ETestContext()
        : base("ETest")
    {

    }

    public DbSet<Categories> Categories { get; set; }
    public DbSet<Products> Products { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Categories>().HasMany<Products>(c => c.Products).WithMany(p => p.Categories)
            .Map(c =>
            {
                c.MapLeftKey("CategoryId");
                c.MapRightKey("ProductId");
                c.ToTable("CategoryProduct");
            });
        base.OnModelCreating(modelBuilder);
    }
}

In the global.asax I am implementing as 在global.asax中,我正在实现为

protected void Application_Start(object sender, EventArgs e)
{
   Database.SetInitializer(new Wb1.Model.ProductsDatabaseInitializer());
   using (var dbContext = new Wb1.Model.ETestContext())
   {
     if (!dbContext.Database.Exists())
     {
       dbContext.Database.Create();
     }
     dbContext.Database.Initialize(true);
   }
}

You should call Initialize instead of Create , it has different implementation with the initializer. 您应该调用Initialize而不是Create ,它与初始化程序具有不同的实现。

Creates a new database on the database server for the model defined in the backing context. 在数据库服务器上为后备上下文中定义的模型创建一个新数据库。 Note that calling this method before the database initialization strategy has run will disable executing that strategy. 请注意,在数据库初始化策略运行之前调用此方法将禁用该策略的执行。 - MSDN -MSDN

And since ProductsDatabaseInitializer is DropCreateDatabaseIfModelChanges , the moment you call Initialize , the database has been created so that the Seed method will not be executed, but if there is a model change, the Seed method will be executed because it's dropped and recreated. 并且由于ProductsDatabaseInitializerDropCreateDatabaseIfModelChanges ,因此在您调用Initialize的那一刻,数据库已经创建,因此不会执行Seed方法,但是如果发生模型更改,则将执行Seed方法,因为它已被删除并重新创建。

The proper way should be just calling the Initialize without checking if it exists or not, because it's already derived from DropCreateDatabaseIfModelChanges , which means create if it doesn't exists and execute the Seed method, or drop and create if model's changed and execute the Seed method, otherwise do nothing. 正确的方法应该只是调用Initialize而不检查它是否存在,因为它已经从DropCreateDatabaseIfModelChanges派生,这意味着如果它不存在则创建并执行Seed方法,或者如果模型已更改并执行Seed则删除并创建方法,否则什么也不做。

Database.SetInitializer(new Wb1.Model.ProductsDatabaseInitializer());
using (var dbContext = new Wb1.Model.ETestContext())
{
    dbContext.Database.Initialize(true);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Database.SetInitializer中的DropCreateDatabaseIfModelChanges - DropCreateDatabaseIfModelChanges in Database.SetInitializer 放置Database.SetInitializer的地方 - Place to put Database.SetInitializer 使用Database.SetInitializer避免Shotgun手术 - Avoiding Shotgun Surgery with Database.SetInitializer Database.SetInitializer(new MigrateDatabaseToLatestVersion <Context, Configuration> ()); 错误 - Database.SetInitializer(new MigrateDatabaseToLatestVersion<Context, Configuration>()); Error Database.SetInitializer的目的 <ArContext> (null)在存储库中? - purpose of Database.SetInitializer<ArContext>(null) inside of repository? 为什么EF4.1 CodeFirst即使没有“ Database.SetInitializer &lt;&gt;()”调用也会创建数据库? - Why is EF4.1 CodeFirst is creating a database even without a `Database.SetInitializer<>()` call? 我可以将我的Database.SetInitializer调用放入具有基本字符串而不是静态构造函数的上下文构造函数中吗? - Can I put my Database.SetInitializer call in the context constructor with the base string instead of a static constructor? WebSecurity.InitializeDatabaseConnection,SetInitializer和Database.Initialize - WebSecurity.InitializeDatabaseConnection, SetInitializer and Database.Initialize 在 MySql.Data.EntityFrameworkCore 中找不到数据库 SetInitializer - Database SetInitializer is not found in MySql.Data.EntityFrameworkCore 数据库初始化程序不播种 - Database initializer not seeding
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM