运行时不应用EF种子

时间:2018-12-17 14:38:41

标签: c# entity-framework seeding

我需要向数据库中添加一些虚拟数据,并想按here所述使用Seed,但是我无法使其正常工作。当我运行Update-database时,它说它正在运行Seed方法,但是完成后,数据库中仍然没有任何内容。这是我的代码(某些字段是缩写)

public class AppContext : DbContext
{
    public AppContext (): base("name=DefaultConnection")
    {
        Database.SetInitializer(new DBContextInitializer()); //Used for seeding. 
    }
    public virtual DbSet<Attendee> Attendees { get; set; }  
}



 public class DBContextInitializer: CreateDatabaseIfNotExists<AppContext>
    {
        protected override void Seed(AppContext context)
        {
            var attendee = new Attendee { Id = 0, FirstName = "XXX" };
            context.Attendees.Add(attendee);
            base.Seed(context);
        }
    }

2 个答案:

答案 0 :(得分:0)

您可能需要在Database.SetInitializer方法中传递AppContext DbContext类。请尝试以下操作,编译并运行更新数据库

public class AppContext : DbContext
{
    public AppContext(): base("name=DefaultConnection")
    {
        Database.SetInitializer<AppContext>(new DBContextInitializer<AppContext>()); //Used for seeding. 
    }
    public virtual DbSet<Attendee> Attendees { get; set; }  
}




public class DBContextInitializer<T> : DropCreateDatabaseAlways<AppContext>
    {
        protected override void Seed(AppContext context)
        {
            var attendee = new Attendee { Id = 0, FirstName = "XXX" };
            context.Attendees.Add(attendee);
            base.Seed(context);
        }
    }

答案 1 :(得分:0)

显然,在Migratons / configuration.cs中已经定义了Seed方法,但是所有语句均已注释!在此处添加我自己的种子代码即可解决该问题。