Asp.net mvc 4如何使用WebSecurity.使用自定义字段创建userandaccount

本文关键字:自定义 字段 创建 userandaccount WebSecurity mvc net 何使用 Asp | 更新日期: 2023-09-27 18:03:23

我有一个问题,我在UserProfile表中创建一个自定义字段,如

public class UserProfile
    {
        [Key]
        [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
        public int UserId { get; set; }
        public int? AddressId { get; set; }
        public int? UserDetailId { get; set; }
        public string UserName { get; set; }

        public UserDetail UserDetail { get; set; }

    }
   public class RegisterModel
    {
        [Required]
        [Display(Name = "User name")]
        public string UserName { get; set; }
        [Required]
        [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
        [DataType(DataType.Password)]
        [Display(Name = "Password")]
        public string Password { get; set; }
        [DataType(DataType.Password)]
        [Display(Name = "Confirm password")]
        [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
        public string ConfirmPassword { get; set; }
        public virtual UserDetail UserDetail { get; set; }
    }
     public class UserDetail 
     {
         public int Id{get;set;}
         public string FirstName{get;set;}    
         public string LastName{get;set;} 
     }

我还将UserDetail添加到DbContext

  public DbSet<UserDetail> UserDetails{get;set;}

问题是当我使用

Web  WebSecurity.CreateUserAndAccount(model.UserName, model.Password, 
                        new { UserDetail = new UserDetail ()
                        }, false);

总是出现一些错误,如:没有映射存在从对象类型…但如果我定义一个简单的类型(如string, int)而不是UserDetail,它工作得很好。

谁能帮我解决这个问题?非常感谢!!

Asp.net mvc 4如何使用WebSecurity.使用自定义字段创建userandaccount

我有一个类似的问题,并使其工作:

将UserDetail和UserProfile组合成一行:

public class UserProfile
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int UserId { get; set; }
    public string UserName { get; set; }
    public string FirstName{get;set;}    
    public string LastName{get;set;}
}

更新你的[HttpPost] Register

WebSecurity.CreateUserAndAccount(model.UserName, model.Password, 
   propertyValues: new { FirstName= model.FirstName, LastName = model.LastName}, false);

不要忘记根据需要在RegisterModel中添加新字段

public class RegisterModel
{
    ....
    public string FirstName{get;set;}    
    public string LastName{get;set;}
}

希望这对你有用

我想你是想这样做的。

UserDetail

public class UserDetail 
 {
     //This is property mapping, UserId will be the same as the Membership UserId and UserProfile UserId
     [Key]
     [ForeignKey("UserProfile")]
     [HiddenInput(DisplayValue = false)]
     public int UserId { get; set; }
     public string FirstName{get;set;}    
     public string LastName{get;set;}
     public UserProfile UserProfile { get; set; } 
 }

RegisterModel

public class RegisterModel
{
    [Required]
    [Display(Name = "User name")]
    public string UserName { get; set; }
    [Required]
    [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
    [DataType(DataType.Password)]
    [Display(Name = "Password")]
    public string Password { get; set; }
    [DataType(DataType.Password)]
    [Display(Name = "Confirm password")]
    [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
    public string ConfirmPassword { get; set; }
    [Required]
    public string FirstName{get;set;}
    [Required]   
    public string LastName{get;set;}
 }
<<p> 注册行动/strong>
//
    // GET: /Account/Register
    [AllowAnonymous]
    public ActionResult Register()
    {
        return View();
    }
    //
    // POST: /Account/Register
    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public ActionResult Register(RegisterModel model)
    {
        if (ModelState.IsValid)
        {
            var db = new UsersContext();
            // Attempt to register the user
            try
            {
               var userProfile = WebSecurity.CreateUserAndAccount(model.UserName, model.Password, null, false);
                //var userProfile= db.UserProfile.SingleOrDefault(u => u.UserName == model.UserName);
                if (userProfile!= null) //This way Userdetail is only created if UserProfile exists so that it can retrieve the foreign key
                {
                    var userDetail = new UserDetail
                                           {
                                               UserProfile = userProfile,
                                               FirstName = model.FirstName,
                                               LastName = model.LastName
                                           };                                                
                    db.UserDetails.Add(userDetail);
                    db.SaveChanges();
                }                    
            }
            catch (MembershipCreateUserException e)
            {
                ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
            }
        }
        // If we got this far, something failed, redisplay form
        return View(model);
    }

编辑

根据您如何设置上下文和存储库,您将需要为每个POCO类设置如下内容

    public DbSet<UserProfile> UserProfiles { get; set; }
    IQueryable<UserProfile> IDataSource.UserProfiles
    {
        get { return UserProfiles; }
    }

除了simplemmembership表之外,您还需要在Membership and Roles

之间的many-to-many上下文中添加以下内容
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Membership>()
          .HasMany<Role>(r => r.Roles)
          .WithMany(u => u.Members)
          .Map(m =>
          {
              m.ToTable("webpages_UsersInRoles");
              m.MapLeftKey("UserId");
              m.MapRightKey("RoleId");
          });
    }