这是我的Context类
public class TestContext : IdentityDbContext<ApplicationUser>
{
public TestContext()
: base("DefaultConnection")
{
}
public DbSet<UserTestModel> UserTestModel { get; set; }
public DbSet<SubscriptionTestModel> SubscriptionTestModel { get; set; }
public DbSet<QATestModel> QATestModel { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
Database.SetInitializer(new TestContextInitializer());
}
}
这是初始化类
public class TestContextInitializer : DropCreateDatabaseAlways<TestContext>
{
protected override void Seed(TestContext context)
{
var user = new List<UserTestModel>{
new UserTestModel{
Id="1",
UserName="Admin",
Password="Admin123"
},
new UserTestModel{
Id="2",
UserName="User",
Password="User123"
}
};
user.ForEach(d=>context.UserTestModel.Add(d));
}
}
在此代码中DropCreateDatabaseAlways
不丢弃数据库。数据库不包含任何外键或关系。
如何解决这个问题?
答案 0 :(得分:0)
在Global.asax文件中添加以下内容:
protected void Application_Start(object sender, EventArgs e)
{
Database.SetInitializer<TestContext>(new TestContextInitializer());
}
它对我有用。这是一个很棒的视频如何使用种子数据填充数据库:
https://www.youtube.com/watch?v=XED_WgDmK4c
如果你从测试方法中调用它,那么这应该可以解决问题:
Database.SetInitializer<TestContext>(new TestContextInitializer());
_dataCntx = new TestContext();
_dataCntx.Database.Initialize(true);