2013-03-12 16 views
12

mam problem z utworzyć pola niestandardowego w UserProfile table.likeAsp.net MVC 4, jak korzystać z niestandardowego pola WebSecurity.createUserAndAccount

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

I ja również dodaje UserDetail do DbContext klasa

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

problem jest wtedy, gdy używam

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

to ALW ays zawiera błąd podobny do: Brak odwzorowania z typu obiektu ... Ale jeśli zdefiniuję prosty typ (jak string, int) zamiast UserDetail, to działa dobrze.

Ktoś może mi pomóc rozwiązać ten problem? Dziękuję bardzo!!

Odpowiedz

12

Miałem podobny problem do tego, ale to działało przez:

połączyć UserDetail i UserProfile coś wzdłuż tej linii:

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

zaktualizować swój [HttpPost] Rejestracja

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

nie zapomnij dodać nowych pól do swojego modułu rejestracji w razie potrzeby

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

Mam nadzieję, że to zadziała

4

Myślę, że chcesz to zrobić.

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

Rejestracja Action

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

Edit

W zależności od sposobu skonfigurowania kontekst i repozytoriów, trzeba będzie coś jak poniżej dla każdej z klas POCO

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

oprócz SimpleMembership tabel, trzeba będzie dodać po do kontekstu dla many-to-many między Membership and Roles

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

jestem testowania kodu, ale mówi mój kontekst nie zawierają definicji dla UserProfile lub UserDetails! Czy mamy dodać coś do naszego kontekstu db? Utknąłem z tym też! – Ciwan

+0

@Ciwan zobacz edytuj w odpowiedzi – Komengem

+0

Dzięki, udało mi się ominąć problem, który miałem, jednak otrzymuję 'null' w tej linii' var userProfile = context.UserProfiles.SingleOrDefault (u => u.UserName == model.UserName); "jakikolwiek powód? Kiedy sprawdzam Db, nazwa użytkownika została utworzona, ale tabela UserDetails jest pusta, oczywiście dlatego, że ta linia zwraca wartość null. – Ciwan

Powiązane problemy