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

问题描述

我试图将用户和角色引入我的数据库。
目前在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

我得到以下错误:

冒险行代码是 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.WebDataAdd reference WebMatrix.WebData version 2.Error will stop.

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

09-24 15:14