无法播种用户和角色

2024-04-25

我正在尝试将用户和角色植入我的数据库中。 目前在 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:行 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 endingMigrations、字符串 targetMigrationId、字符串 lastMigrationId) 在 System.Data.Entity.Migrations.Infrastruct.MigratorLoggingDecorator.Upgrade(IEnumerable`1 endingMigrations、字符串 targetMigrationId、字符串 lastMigrationId) 在 System.Data.Entity.Migrations.DbMigrator.Update(字符串 targetMigration) 在 System.Data.Entity.Migrations.Infrastruct.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 但没有成功。我在互联网上寻找可能的解决方案,但没有一个有效(包括其他堆栈溢出文章)。下面是一些值得注意的博客文章。

  • http://blog.longle.net/2012/09/25/seeding-users-and-roles-with-mvc4-simplemembershipprovider-simpleroleprovider-ef5-codefirst-and-custom-user-properties/ http://blog.longle.net/2012/09/25/seeding-users-and-roles-with-mvc4-simplemembershipprovider-simpleroleprovider-ef5-codefirst-and-custom-user-properties/
  • http://odetocode.com/Blogs/scott/archive/2012/08/31/seeding-membership-amp-roles-in-asp-net-mvc-4.aspx http://odetocode.com/Blogs/scott/archive/2012/08/31/seeding-membership-amp-roles-in-asp-net-mvc-4.aspx

请参阅下面的代码。

[配置.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);
}
}

正常登录我的网站与此处的此功能完美配合。

[网络配置]

 <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; }

}

UPDATE

我认为 WebSecurity.InitializeDatabaseConnection 甚至没有运行 - 我可以在我的 Seed 方法中放置多个,并且不会出现通常会出现的“只能调用一次”错误。

我的种子方法与所有模型一起位于我的域项目中,而其他所有内容都位于 WebUI 项目中。不确定这是否与此有关。


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

protected override void Seed(GratifyGaming.Domain.Models.DAL.GratifyGamingContext context)
{
    if (!WebSecurity.Initialized)
    {
        WebSecurity.InitializeDatabaseConnection("DefaultConnection",
                                                 "UserProfile",
                                                 "UserId",
                                                 "UserName",
                                                 autoCreateTables: true);
    }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

无法播种用户和角色 的相关文章

随机推荐

  • 触发其他配置并使用 Jenkins 发送当前构建状态

    在某个 Jenkins 配置中 我希望触发另一个配置 post建立行动 我想将当前构建状态作为参数之一传递 IE 表示状态 SUCCESS FAIL UNSTABLE 的字符串 int 我有两个选项来创建构建后触发器 Using the j
  • 示例软键盘双字母

    我是 android 的初学者开发人员 我下载了示例 SoftKeyboard 的源代码 https android googlesource com platform development android 2 3 3 r1 1 samp
  • 添加新数据源(mysql)wildfly

    我正在尝试将新的数据源 mysql jdbc 驱动程序添加到我的 Wildfly 服务器 我创建了文件夹 wildfly x x x modules system layers base com mysql main 我这里有 jdbc j
  • 我可以将 Coq 证明提取为 Haskell 函数吗?

    自从学了一点 Coq 以来 我就想学着写一个所谓的除法算法的 Coq 证明 它实际上是一个逻辑命题 forall n m nat exists q nat exists r nat n q m r 我最近利用我学到的知识完成了这项任务软件基
  • 如何对二维 Java 数组进行切片?

    folks 我正在使用 JTables 并有一个二维数组 我需要删除数组中每一行的第一个元素 除此之外还有更简单的方法吗 int height data2 length int width data2 0 length Object dat
  • 需要帮助了解主干中嵌套视图的基础知识

    我一直在阅读有关backbone js 中嵌套视图的大量内容 并且了解其中的很多内容 但仍然令我困惑的一件事是 如果我的应用程序有一个 shell 视图 其中包含页面导航 页脚等子视图 这些子视图在使用应用程序的过程中不会改变 那么我是否需
  • 将 ListView 中的 SelectedItems 绑定到 Windows Phone 8.1 中的 ViewModel

    我有以下代码
  • Python / Pandas - 用于查看数据帧或矩阵的 GUI [关闭]

    Closed 这个问题正在寻求书籍 工具 软件库等的推荐 不满足堆栈溢出指南 help closed questions 目前不接受答案 我正在使用 Pandas 包 它创建一个 DataFrame 对象 它基本上是一个标记矩阵 通常 我的
  • Laravel mix,在resources中调用app.js

    我有一个带有 laravel 和 vuejs 的网络应用程序 我使用 laravel mix 并且在我的 webpack mix js 中我有 mix js resources assets js app js public js 在我看来
  • 我收到来自 php 和 js 的空白电子邮件

    请帮助我解码真正的问题是什么 问题是 尽管我对此代码进行了所有调整和研究 但我仍然收到一封空白电子邮件 下面是我的 html javascript ajax 和 php 代码 HTML 代码 名为 contact html 的文件
  • PHP echo 与 PHP 短 echo 标签

    它们的安全性相同吗 我被告知使用 或者 当在 JavaScript 内回显数据时 它必须是 JavaScript 编码的
  • SQL Server 的 mysqldump 等效项

    SQL Server 是否有与 MySQL 具有 mysqldump 等效的模式和数据导出 转储工具 试图重新定位旧的 ASP 站点 但我对在 Windows 服务器上工作感到很不高兴 注意 DTS 导出实用程序自己似乎可以导出数据 而无需
  • 高效生成所有小于 N 的合数(及其因式分解)

    我想构建一个高效的 Python 迭代器 生成器 它会产生 所有小于 N 的合数 连同他们的质因数分解 我将其称为 composites with factors 假设我们已经有小于 N 的素数列表 或者可以执行相同操作的素数生成器 请注意
  • 根记录器忽略记录器级别

    根记录器在 我认为 应该记录时不会记录 import logging NOTE I make sure to set the root logger level to logging DEBUG logging basicConfig fo
  • 在 SPSS 18 中指定相对路径

    在 SPSS 11 中可以指定相对路径 例子 FILE HANDLE myfile data current txt LRECL 533 DATA LIST FILE myfile 这之所以有效 是因为 SPSS 11 将工作文件夹设置为源
  • 操作员 '??'不能应用于类型“T”和“T”的操作数

    我有以下通用方法 但 VS 给了我一个编译错误 运算符 不能应用于 T 和 T 类型的操作数 public static T Method
  • Google 地图 - 未捕获 InvalidValueError:初始化不是函数

    当我加载 Google 地图显示的页面时 我总是在控制台中看到以下错误 未捕获的 InvalidValueError 初始化不是函数js 传感器 假 回调 初始化 94 将鼠标悬停在文件名上时 这显示为源自 谷歌地图窗口和地图显示得非常好
  • 在RequiredFieldValidator 触发后调用JavaScript 方法?

    表单元素被视为无效后是否可以触发 JavaScript 方法 这是我的场景 ASPX 页面上有 2 个选项卡 用户必须在两个选项卡上填写信息 用户在选项卡 2 上单击提交按钮 但是 第一个选项卡上有一个必填字段需要注意 我是否需要创建自定义
  • 无法使用 conda 安装 mpi4py 并指定预安装的 mpicc 路径

    我已经尝试安装mpi4py with env MPICC path to openmpi bin mpicc conda install c anaconda mpi4py 但我收到这样的消息 The following NEW packa
  • 无法播种用户和角色

    我正在尝试将用户和角色植入我的数据库中 目前在 C MVC4 中使用具有自动迁移功能的 Code First 实体框架 每当我打电话 更新数据库 强制 我收到以下错误 运行种子方法 System InvalidOperationExcept