Asp.net mvc 4 как использовать WebSecurity.createUserAndAccount с настраиваемым полем
У меня проблема с созданием настраиваемого поля в UserProfile
table.like
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
, он отлично работает.
Кто-нибудь может помочь мне решить эту проблему? Большое спасибо!
Ответы
Ответ 1
У меня была схожая проблема с этим и заработала:
объединить 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]
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;}
}
надеюсь, что это сработает для вас
Ответ 2
Я думаю, вы хотите это сделать.
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;}
}
Действие регистрации
//
// 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
В зависимости от того, как вы настроили свой Контекст и репозитории, вам понадобится что-то вроде ниже для каждого из ваших классов POCO
public DbSet<UserProfile> UserProfiles { get; set; }
IQueryable<UserProfile> IDataSource.UserProfiles
{
get { return UserProfiles; }
}
В дополнение к таблицам SimpleMembership вам нужно добавить в свой контекст для many-to-many
между 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");
});
}