11

我正在尝试向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-特性/

但我什么都想不出来......我的WebMatrix.WebData版本是v4.0.30319

有什么想法吗?

4

2 回答 2

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

这是nice tutorial关于您可能会考虑使用的 SimpleMembershipProvider 的内容。

于 2013-01-26T22:43:34.720 回答
0

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

        membership.CreateUserAndAccount(
            "drew", 
            "password",
            new Dictionary<string, object> { new { "Email", "myemail@gmail.com" } }
        );
于 2013-01-26T22:49:02.877 回答