2

ユーザーとロールをデータベースにシードしようとしています。現在、C# MVC4 の自動移行で Code First Entity Framework を使用しています。私が電話するたびに

更新データベース -強制

次のエラーが表示されます。

シード メソッドを実行します。System.InvalidOperationException: 「WebSecurity」クラスの他のメソッドを呼び出す前に、「WebSecurity.InitializeDatabaseConnection」メソッドを呼び出す必要があります。この呼び出しは、サイトのルートにある _AppStart.cshtml ファイルに配置する必要があります。WebMatrix.WebData.SimpleRoleProvider.get_PreviousProvider() で WebMatrix.WebData.SimpleRoleProvider.RoleExists(String roleName) で System.Web.Security.Roles.RoleExists(String roleName) で GratifyGaming.Domain.Migrations.Configuration.Seed(GratifyGamingContext コンテキスト) C:\Users\Unreal\Documents\Visual Studio 2010\Projects\GratifyGaming\GratifyGaming.Domain\Migrations\Configuration.cs: System.Data.Entity.Migrations.DbMigrationsConfiguration の 36 行目1.OnSeed(DbContext context) at System.Data.Entity.Migrations.DbMigrator.SeedDatabase() at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.SeedDatabase() at System.Data.Entity.Migrations.DbMigrator.Upgrade(IEnumerableSystem.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.Upgrade(IEnumerable`1 pendingMigrations、文字列 targetMigrationId、文字列 lastMigrationId) で System.Data.Entity.Migrations.DbMigrator.Update(文字列 targetMigration) で 1 pendingMigrations、文字列 targetMigrationId、文字列 lastMigrationId) ) System.Data.Entity.Migrations.Infrastructure.MigratorBase.Update(String targetMigration) で System.Data.Entity.Migrations.Design.ToolingFacade.UpdateRunner.RunCore() で System.Data.Entity.Migrations.Design.ToolingFacade で。 BaseRunner.Run() 「WebSecurity」クラスの他のメソッドを呼び出す前に、「WebSecurity.InitializeDatabaseConnection」メソッドを呼び出す必要があります。この呼び出しは、サイトのルートにある _AppStart.cshtml ファイルに配置する必要があります。

問題のあるコード行はRole.Exists

WebSecurity.InitializeDatabaseConnection を Global.asax、Seed() に配置しようとしましたが、成功せずに _AppStart.cshtml を作成しました。私は可能な解決策を探してインターネットをトロールしましたが、どれもうまくいきませんでした(他のスタックオーバーフローの記事を含む)。いくつかの注目すべきブログ投稿を以下に示します。

以下のコードを参照してください。

[構成.cs]

 protected override void Seed(GratifyGaming.Domain.Models.DAL.GratifyGamingContext context)
    {
        var criteria = new List<Criterion>
        {
            new Criterion { ID = 1, IsMandatory=true, Name = "Gameplay", Description="The playability of the games core mechanics" },
            new Criterion { ID = 2, IsMandatory=true, Name = "Art Style", Description="The artistic feel of the game as a whole. Elements such as story, style and originality come into play." },
            new Criterion { ID = 3, IsMandatory=true, Name = "Longevity", Description="How long did this game keep you entertained?" },
            new Criterion { ID = 4, IsMandatory=true, Name = "Graphics", Description="How good does the game look?" }
        };

        criteria.ForEach(s => context.Criterion.AddOrUpdate(s));
        context.SaveChanges();


        if (!Roles.RoleExists("Administrator"))
            Roles.CreateRole("Administrator");

        if (!WebSecurity.UserExists("user"))
            WebSecurity.CreateUserAndAccount(
                "user",
                "password");

        if (!Roles.GetRolesForUser("lelong37").Contains("Administrator"))
            Roles.AddUsersToRoles(new[] { "user" }, new[] { "Administrator" });
    }

Criterion シード コードは確実に機能します。

[_AppStart.cshtml]

@{
 if (!WebSecurity.Initialized)
{
    WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId",
                                             "UserName", autoCreateTables: true);
}
}

私のサイトへの通常のログインは、ここにあるこれで完全に機能します。

[web.config]

 <roleManager enabled="true" defaultProvider="SimpleRoleProvider">
  <providers>
    <clear/>
    <add name="SimpleRoleProvider" type="WebMatrix.WebData.SimpleRoleProvider, WebMatrix.WebData"/>
  </providers>
</roleManager>
<membership defaultProvider="SimpleMembershipProvider">
  <providers>
    <clear/>
    <add name="SimpleMembershipProvider" type="WebMatrix.WebData.SimpleMembershipProvider, WebMatrix.WebData" />
  </providers>
</membership>

[AccountModel.cs]

    [Table("UserProfile")]
public class UserProfile
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int UserId { get; set; }
    public string UserName { get; set; }
    public string Email { get; set; }
    public virtual ICollection<Game> AttachedGames { get; set; }

    public virtual ICollection<UserGratificationRecord> GratificationHistory { get; set; }

    [ForeignKey("UserLevel")]
    public int? AcheivementID { get; set; }
    public virtual Acheivement UserLevel { get; set; }

    public int? NumOfGratifictions { get; set; }

}

アップデート

WebSecurity.InitializeDatabaseConnection は実行されていないと思います.Seed メソッドに複数配置できますが、通常発生する「一度だけ呼び出すことができます」というエラーは発生しません。

私のシード メソッドはすべてのモデルと共に私のドメイン プロジェクトにあり、他のすべては WebUI プロジェクトにあります。これが何か関係があるかどうかはわかりません。

4

3 に答える 3

4

その怠惰な init を Seed メソッドの先頭に入れるだけです

protected override void Seed(GratifyGaming.Domain.Models.DAL.GratifyGamingContext context)
{
    if (!WebSecurity.Initialized)
    {
        WebSecurity.InitializeDatabaseConnection("DefaultConnection",
                                                 "UserProfile",
                                                 "UserId",
                                                 "UserName",
                                                 autoCreateTables: true);
    }
于 2012-11-30T21:55:03.617 に答える
1

App_Startに、次を追加してみてください。

        var configuration = new Data.Migrations.Configuration();
        var migrator = new DbMigrator(configuration);
        migrator.Update();

configuration.csファイルを公開する必要があります

  public class Configuration : DbMigrationsConfigurati

これにより、プログラムの実行時にシードメソッドが呼び出されるようになります

于 2012-12-02T00:43:27.763 に答える
0

WebMatrix.WebData への既存の参照を削除します。参照 WebMatrix.WebData バージョン 2 を追加します。エラーは停止します。

于 2012-12-02T03:16:48.503 に答える