[英]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. 并且由于ProductsDatabaseInitializer
是DropCreateDatabaseIfModelChanges
,因此在您调用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.