【问题标题】:Cannot seed Users & Roles无法播种用户和角色
【发布时间】:2012-11-13 23:01:18
【问题描述】:

我正在尝试将用户和角色播种到我的数据库中。 目前在 C# MVC4 中使用具有自动迁移功能的 Code First 实体框架。 每当我打电话时

更新-数据库-强制

我收到以下错误:

运行种子方法。 System.InvalidOperationException:您必须调用 “WebSecurity.InitializeDatabaseConnection”方法之前调用任何 “WebSecurity”类的其他方法。这个电话应该放在 站点根目录中的 _AppStart.cshtml 文件。 在 WebMatrix.WebData.SimpleRoleProvider.get_PreviousProvider() 在 WebMatrix.WebData.SimpleRoleProvider.RoleExists(字符串角色名称) 在 System.Web.Security.Roles.RoleExists(字符串角色名称) 在 GratifyGaming.Domain.Migrations.Configuration.Seed(GratifyGamingContext 上下文)在 C:\Users\Unreal\Documents\Visual Studio 2010\Projects\GratifyGaming\GratifyGaming.Domain\Migrations\Configuration.cs:line 36 在 System.Data.Entity.Migrations.DbMigrationsConfiguration1.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(IEnumerable1 pendingMigrations,字符串 targetMigrationId,字符串 lastMigrationId) 在 System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.Upgrade(IEnumerable`1 pendingMigrations,字符串 targetMigrationId,字符串 lastMigrationId) 在 System.Data.Entity.Migrations.DbMigrator.Update(字符串 targetMigration) 在 System.Data.Entity.Migrations.Infrastructure.MigratorBase.Update(字符串 目标迁移) 在 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" });
    }

标准种子代码可以正常工作。

[_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 项目中。不确定这是否与它有关。

【问题讨论】:

    标签: asp.net-mvc entity-framework c#-4.0 seed simplemembership


    【解决方案1】:

    只需将惰性初始化放入 Seed 方法的顶部

    protected override void Seed(GratifyGaming.Domain.Models.DAL.GratifyGamingContext context)
    {
        if (!WebSecurity.Initialized)
        {
            WebSecurity.InitializeDatabaseConnection("DefaultConnection",
                                                     "UserProfile",
                                                     "UserId",
                                                     "UserName",
                                                     autoCreateTables: true);
        }
    

    【讨论】:

    • 有趣的是,它在 Seed 方法中找不到 WebSecurity.Initialized - 错误 3“WebMatrix.WebData.WebSecurity”不包含“Initialized”的定义
    • 我在我的域项目中引用了旧版本的 WebMatrix.WebData。我参考了 v2,添加了您的代码,现在它可以工作了。
    • +1 表示 if (!WebSecurity.Initialized)。我的 Seed() 方法被调用了两次!奇怪的是,第二次调用似乎是从 Seed 方法本身的主体内部触发的(即从我访问迁移期间新创建的 DbSet 之一的代码行开始)。如果没有 WebSecurity.Initialized 检查,第二次 Seed() 调用会导致“只能调用一次“WebSecurity.InitializeDatabaseConnection”方法。”
    【解决方案2】:

    在您的 App_Start 中,尝试添加:

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

    您必须公开您的 configuration.cs 文件

      public class Configuration : DbMigrationsConfigurati
    

    这应该会在您运行程序时调用您的种子方法

    【讨论】:

    • 感谢您的意见 TMan。添加您建议的代码会出现以下错误:错误 6 名称空间“WebMatrix.Data”中不存在类型或名称空间名称“Migrations”(您是否缺少程序集引用?)
    【解决方案3】:

    删除您对 WebMatrix.WebData 的现有引用 添加参考 WebMatrix.WebData 版本 2。 错误将停止。

    【讨论】:

    • 请问如何引用 WebMatrix.WebData 版本 2?
    • 你可以把它添加到 web.config
    猜你喜欢
    • 2021-07-10
    • 1970-01-01
    • 1970-01-01
    • 2020-09-13
    • 2020-02-25
    • 1970-01-01
    • 1970-01-01
    • 2016-10-03
    • 2013-10-17
    相关资源
    最近更新 更多