[英]Entity Framework ASP.NET MVC6 in Identity Model, Creating a new record instead of linking it to existing record
有人在这里发布了相同的问题,我按照每个步骤进行操作,但仍然无法正常工作。 之前,我使用相同的功能进行了许多工作项目。
因此,当用户注册一个新帐户时,他填写了一个表格并从2个下拉列表中选择UserType和Region。
一切正常,并且在发布表单时。 在数据库中创建了Region和UserType的新记录,并与新ID链接。
这是我的IdentityModel:
public class ApplicationUser : IdentityUser
{
[Required]
public string Name { get; set; }
public UserType UserType { get; set; }
public int UserTypeId { get; set; }
public Region Region { get; set; }
public int RegionId { get; set; }
[Display(Name ="Summoner Name")]
public string SummonerName { get; set; }
public int AccountId { get; set; }
public async Task<ClaimsIdentity>
GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
// etc.....
这是我在AccountController中的注册操作
public async Task<ActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
var UserTypeInDb = _context.UserTypes.Single(u => u.Id == model.UserTypeId);
var RegionInDb = _context.Regions.Single(u => u.Id == model.RegionId);
var user = new ApplicationUser {
UserName = model.Email,
Email = model.Email,
Name = model.Name,
Region = RegionInDb,
UserType = UserTypeInDb
};
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);
// For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=320771
// Send an email with this link
// string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
// var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
// await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");
return RedirectToAction("Index", "Home");
}
AddErrors(result);
}
// If we got this far, something failed, redisplay form
var viewModel = new RegisterViewModel()
{
Regions = _context.Regions.ToList(),
UserTypes = _context.UserTypes.ToList()
};
return View(viewModel);
}
2个变量UserTypeInDb和RegionInDb包含具有正确ID的正确记录。
那到底是什么错呢? 谢谢
我固定了它而不更改ApplicationUser类
var user = new ApplicationUser {
UserName = model.Email,
Email = model.Email,
RegionId = RegionInDb.Id, <-------
UserTypeId = UserTypeInDb.Id, <------- the fix
UserType = UserTypeInDb
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.