我面临同样的问题,我想出的解决方案是在配置器中公开一个种子事件,并让应用程序使用它订阅 SimpleMembership 种子。
一、配置:
internal sealed class Configuration : DbMigrationsConfiguration<MyContext>
{
public event EventHandler<MyContext> OnSeed;
public Configuration()
{
AutomaticMigrationsEnabled = false;
}
protected override void Seed(MyContext context)
{
var onSeed = this.OnSeed;
if (onSeed != null)
onSeed(this, context);
// This method will be called after migrating to the latest version.
// You can use the DbSet<T>.AddOrUpdate() helper extension method
// to avoid creating duplicate seed data. E.g.
//
// context.People.AddOrUpdate(
// p => p.FullName,
// new Person { FullName = "Andrew Peters" },
// new Person { FullName = "Brice Lambson" },
// new Person { FullName = "Rowan Miller" }
// );
//
}
}
然后,为了能够将它与 Database.SetInitializer 一起使用,我基于 MigrateDatabaseToLatestVersion 创建了自己的 IDatabaseInitializer。这很容易做到,因为正如这篇文章所说(你可以在这里查看),它只是 DbMigration 的一个包装器。
public class MyDatabaseInitializer : IDatabaseInitializer<MyContext>
{
private readonly Configuration config;
public event EventHandler<MyContext> OnSeed
{
add { if (this.config != null) this.config.OnSeed += value; }
remove { if (this.config != null) this.config.OnSeed -= value; }
}
/// <summary>
/// Initializes a new instance of the MigrateDatabaseToLatestVersion class.
/// </summary>
public MyDatabaseInitializer()
{
this.config = new Configuration();
}
/// <summary>
/// Initializes a new instance of the MigrateDatabaseToLatestVersion class that will
/// use a specific connection string from the configuration file to connect to
/// the database to perform the migration.
/// </summary>
/// <param name="connectionStringName"> The name of the connection string to use for migration. </param>
public MyDatabaseInitializer(string connectionStringName)
{
Contract.Requires(!string.IsNullOrWhiteSpace(connectionStringName));
this.config = new Configuration
{
TargetDatabase = new DbConnectionInfo(connectionStringName)
};
}
/// <inheritdoc />
public void InitializeDatabase(MyContext context)
{
var migrator = new DbMigrator(config);
migrator.Update();
}
}
在这个初始化程序中,我公开了 OnSeed 事件。在 App_Start 中,在 MVC 项目中,我订阅它以播种 SimpleMembership 数据。
var initializer = new PoipDatabaseInitializer();
initializer.OnSeed += (s, e) => SeedSecurity();
Database.SetInitializer(initializer);
private static void SeedSecurity()
{
WebSecurity.InitializeDatabaseConnection("MyDatabase", "UserProfile", "UserId", "UserName", autoCreateTables: false);
if (!Roles.RoleExists("SysAdmin"))
Roles.CreateRole("SysAdmin");
if (!WebSecurity.UserExists("sysadmin"))
WebSecurity.CreateUserAndAccount(
"sysadmin",
"password"
);
if (!Roles.GetRolesForUser("sysadmin").Contains("SysAdmin"))
Roles.AddUsersToRoles(new[] { "sysadmin" }, new[] { "SysAdmin" });
}