SimpleMemership CreateUserAndAccount Customization

时间:2013-01-26 22:32:31

标签: asp.net-mvc entity-framework asp.net-mvc-4 webmatrix simplemembership

我正在尝试向我的模型中的UserProfile类添加新属性

public class UserProfile
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int UserId { get; set; }
    public string UserName { get; set; }
    [Required]
    [DataType(DataType.EmailAddress)]
    [Display(Name = "Email Address")]
    public string Email { get; set; } \\this is the new property
    public virtual IList<Game> Games { get; set; }
}

我正在尝试将其添加到我的Configurations.cs文件

中的种子方法中
private void SeedMembership()
    {
        WebSecurity.InitializeDatabaseConnection("MafiaContext",
            "UserProfile", "UserId", "UserName", autoCreateTables: true);

        var roles = (SimpleRoleProvider)Roles.Provider;
        var membership = (SimpleMembershipProvider)Membership.Provider;

        if (!roles.RoleExists("Administrator"))
        {
            roles.CreateRole("Administrator");
        }
        if (membership.GetUser("drew", false) == null)
        {

            membership.CreateUserAndAccount(
                "drew", 
                "password", false,
                new { Email = "myemail@gmail.com" }); \\ this line errors
        }
        if (!roles.GetRolesForUser("drew").Contains("Administrator"))
        {
            roles.AddUsersToRoles(new[] { "drew" }, new[] { "Administrator" });
        }
    }

但是,我收到错误:

Error 2 Argument 4: cannot convert from 'AnonymousType#1' to 'System.Collections.Generic.IDictionary<string,object>' C:\Code\Mafia\Mafia.EF\Migrations\Configuration.cs 65 21 Mafia.EF

我已按照示例进行操作,例如:http://blog.longle.net/2012/09/25/seeding-users-and-roles-with-mvc4-simplemembershipprovider-simpleroleprovider-ef5-codefirst-and-custom-user-properties/

但我什么都没有......我的WebMatrix.WebData版本是v4.0.30319

有什么想法吗?

2 个答案:

答案 0 :(得分:20)

试试这样:

private void SeedMembership()
{
    WebSecurity.InitializeDatabaseConnection(
        "MafiaContext",
        "UserProfile", 
        "UserId", 
        "UserName", 
        autoCreateTables: true
    );

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

    if (!WebSecurity.UserExists("drew"))
    {
        WebSecurity.CreateUserAndAccount(
            "drew", 
            "password",
            new { Email = "myemail@gmail.com" },
            false
        );
    }

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

这是关于您可能会考虑通过的SimpleMembershipProvider的nice tutorial

答案 1 :(得分:0)

由于SimpleMembershipProvider.CreateUserAndAccount方法的最后一个参数应为IDictionary<string, Object>,因此您的代码应重写如下:

        membership.CreateUserAndAccount(
            "drew", 
            "password",
            new Dictionary<string, object> { new { "Email", "myemail@gmail.com" } }
        );