我面臨同樣的問題,我想出的解決方案是在配置器中公開種子事件,並讓應用程序訂閱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使用它,我創建了自己IDatabaseInitializer的基礎上,MigrateDatabaseToLatestVersion。這很容易做,因爲,如this post所說(你可以檢查here),它只是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" });
}
有一些技巧可以使SimpleMembership與您的域一起工作,但您可能需要分享更多信息才能獲得有用的答案。您的域名是否與用戶會員信息緊密結合,還是完全獨立?你打算使用OAth嗎?你在播種什麼,它有多重要?播種只是單元測試還是生產需要?在我看來,如果會員和角色信息需要大量的擴展和集成,您最好創建自己的自定義會員和角色提供者。 –