我有以下DbContext
类。关于EF的一切都运转良好(迁移,关系等),唯一对我不起作用的是播种。我尝试了许多不同的解决方案,但似乎没有任何效果。有人知道吗?
当我运行update-database时,似乎执行了seed方法,但是数据库中没有任何更新。
public class ProgramContext : DbContext
{
public ProgramContext() : base("ProgramContext")
{
Database.SetInitializer<ProgramContext>(new MyDbInit());
}
public DbSet<Bin> Bins { get; set; }
public DbSet<Goal> Goals { get; set; }
public DbSet<Queue> Queues { get; set; }
public DbSet<Status> Statuses { get; set; }
public class MyDbInit : DropCreateDatabaseIfModelChanges<ProgramContext>
{
protected override void Seed(ProgramContext context)
{
IList<Status> statuses = new List<Status>();
Status status0 = new Status("WH-RAMP");
Status status1 = new Status("Transport > Lijn");
Status status2 = new Status("In lijn");
Status status3 = new Status("Retour lijn");
Status status4 = new Status("Transport > WH");
context.Statuses.Add(status0);
context.SaveChanges();
base.Seed(context);
}
}
}
Bin.class
public class Bin
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public long BinId { get; set; }
public string Barcode { get; set; }
public Status Status { get; set; }
public bool Full { get; set; }
public Bin(string Barcode, Status Status, bool full)
{
this.Barcode = Barcode;
this.Status = Status;
this.Full = Full;
}
}
Status.class
public class Status
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public long StatusId { get; set; }
public string StatusName { get; set; }
public Status(string StatusName)
{
this.StatusName = StatusName;
}
}
答案 0 :(得分:1)
DropCreateDatabaseIfModelChanges IDatabaseInitializer的实现将仅在自创建数据库以来模型已更改的情况下才删除,重新创建和有选择地重新种子数据库。
这可能会有所帮助。 Configuration类位于migrations文件夹内。
internal sealed class Configuration : DbMigrationsConfiguration<BookService.Models.BookServiceContext>
{
protected override void Seed(BookService.Models.BookServiceContext context)
{
Status status0 = new Status("WH-RAMP");
Status status1 = new Status("Transport> Lijn");
Status status2 = new Status("In lijn");
Status status3 = new Status("Retour lijn");
Status status4 = new Status("Transport > WH");
context.Statuses.Add(status0);
context.Statuses.Add(status1);
context.Statuses.Add(status2);
context.Statuses.Add(status3);
context.Statuses.Add(status4);
}
}