【发布时间】: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