我正在使用 ASP.NET MVC 4 Internet 应用程序模板。我已经成功地将一些自定义表添加到自动创建的现有数据库中,但现在我想在创建数据库后将一些数据播种到我的一个表中。我知道我可以通过覆盖数据库初始化程序上的 Seed 方法来做到这一点,但默认情况下 asp.net mvc4 将初始化程序设置为 null 我不确定我是否更改初始化程序会导致一些新问题或副作用......如何做吗?
// I could implement this custom initializer but as by default is set to null
//
public class UsersContextSeedInitializer : CreateDatabaseIfNotExists<UsersContext>
{
protected override void Seed(UsersContext context)
{
// Populate my table here
}
}
private class SimpleMembershipInitializer
{
public SimpleMembershipInitializer()
{
Database.SetInitializer<UsersContext>(null);
// I could do it here or better below?: Database.SetInitializer(new UsersContextSeedInitializer());
try
{
using (var context = new UsersContext())
{
if (!context.Database.Exists())
{
// Create the SimpleMembership database without Entity Framework migration schema
((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
}
}
// better here?: Database.SetInitializer(new UsersContextSeedInitializer());
WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);
}
catch (Exception ex)
{
throw new InvalidOperationException("The ASP.NET Simple Membership database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588", ex);
}
}
}