不能种子用户&角色 [英] Cannot seed Users & Roles

查看:303
本文介绍了不能种子用户&角色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将用户和角色引入我的数据库。
目前在C#MVC4中使用代码优先实体框架和自动迁移。
每当我呼叫

I am trying to seed users and roles into my database. Currently using Code First Entity Framework with Automatic Migrations in C# MVC4. Whenever I call


Update-Database -Force

Update-Database -Force

我得到以下错误:


运行种子方法。
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)
at GratifyGaming.Domain.Migrations.Configuration.Seed(GratifyGamingContext
context)in C:\Users\Unreal\Documents\Visual Studio
2010\Projects\GratifyGaming\GratifyGaming .Domain \Migrations\Configuration.cs:line
36
在System.Data.Entity.Migrations.DbMigrationsConfiguration 1.OnSeed(DbContext
上下文)
在System.Data.Entity.Migrations.DbMigrator.SeedDatabase()
在System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.SeedDatabase()
在System.Data.Entity.Migrations.DbMigrator .Upgrade(IEnumerable
1
pendingMigrations,String targetMigrationId,String lastMigrationId)
在System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.Upgrade(IEnumerable`1
pendingMigrations,String targetMigrationId,String lastMigrationId)
在System.Data.Entity.Migrations.DbMigrator.Update(String targetMigration)
在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文件中。

Running Seed method. System.InvalidOperationException: You must call the "WebSecurity.InitializeDatabaseConnection" method before you call any other method of the "WebSecurity" class. This call should be placed in an _AppStart.cshtml file in the root of your site. at WebMatrix.WebData.SimpleRoleProvider.get_PreviousProvider() at WebMatrix.WebData.SimpleRoleProvider.RoleExists(String roleName) at System.Web.Security.Roles.RoleExists(String roleName) at GratifyGaming.Domain.Migrations.Configuration.Seed(GratifyGamingContext context) in C:\Users\Unreal\Documents\Visual Studio 2010\Projects\GratifyGaming\GratifyGaming.Domain\Migrations\Configuration.cs:line 36 at 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, String targetMigrationId, String lastMigrationId) at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.Upgrade(IEnumerable`1 pendingMigrations, String targetMigrationId, String lastMigrationId) at System.Data.Entity.Migrations.DbMigrator.Update(String targetMigration) at System.Data.Entity.Migrations.Infrastructure.MigratorBase.Update(String targetMigration) at System.Data.Entity.Migrations.Design.ToolingFacade.UpdateRunner.RunCore() at System.Data.Entity.Migrations.Design.ToolingFacade.BaseRunner.Run() You must call the "WebSecurity.InitializeDatabaseConnection" method before you call any other method of the "WebSecurity" class. This call should be placed in an _AppStart.cshtml file in the root of your site.

冒险行代码是 Role.Exists

我试过把WebSecurity.InitializeDatabaseConnection在Global.asax, Seed(),并创建了一个_AppStart.cshtml没有成功。我已经拖网网络寻找一个可能的解决方案,他们都没有工作(包括其他堆栈溢出文章)。以下是一些重要的网志文章。

I have tried putting the WebSecurity.InitializeDatabaseConnection in Global.asax, Seed(), and created an _AppStart.cshtml with no success. I have trawled the internet looking for a possible solution and none of them have worked (including other stack overflow articles). Some notable blog posts are below.

  • 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

请参阅下面的代码。

[Configuration.cs]

[Configuration.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" });
    }

条件种子代码可以正常工作。

The Criterion seed code works without fail.

[_ AppStart.cshtml]

[_AppStart.cshtml]

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

正常登录我的网站。

[web.config]

[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]

[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方法中放置多个,

I think the WebSecurity.InitializeDatabaseConnection is not even being run - I can place more than one in my Seed method, and not get the 'can only be called once' error that you would normally get.

我的种子方法是在我的域项目中与所有的模型,而一切都在一个WebUI项目。

My seed method is in my domain project along with all the models, while everything else is in a WebUI project. Not sure if this has anything to do with it.

推荐答案

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

Delete your existing reference to WebMatrix.WebData Add reference WebMatrix.WebData version 2. Error will stop.

这篇关于不能种子用户&amp;角色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆