Asp.net mvc 如何在asp.net identity MVC项目中添加外键
使用IdentityUser继承的ApplicationUser类Asp.net mvc 如何在asp.net identity MVC项目中添加外键,asp.net-mvc,entity-framework-6,asp.net-identity,asp.net-identity-2,Asp.net Mvc,Entity Framework 6,Asp.net Identity,Asp.net Identity 2,使用IdentityUser继承的ApplicationUser类 public class ApplicationUser : IdentityUser { public DateTime BirthDate { get; set; } public string User_type { get; set; } public DateTime CreatedOn { get; set; } public Enums.Sex Gender { get; set;
public class ApplicationUser : IdentityUser
{
public DateTime BirthDate { get; set; }
public string User_type { get; set; }
public DateTime CreatedOn { get; set; }
public Enums.Sex Gender { get; set; }
public bool IsActive { get; set; }
public virtual Patient Patients { get; set; }
public int PatientID { get; set; }
}
病人类别
public class Patient
{
[Key]
public int PatientID { get; set; }
public string ProfilePicture { get; set; }
public string FName { get; set; }
public DateTime BirthDate { get; set;}
public string City { get; set; }
public string Country { get; set; }
}
控制器
public async Task<ActionResult> RegisterPatient(RegisterViewModel model)
{
MYDb db = new MYDb();
Patient pt = new Patient();
pt.BirthDate = model.BirthDate;
pt.City = model.City;
pt.Country = model.Country;
pt.ProfilePicture = model.ProfilePicture;
pt.FName = model.FName;
int Pat_id = model.PatientID;
if (ModelState.IsValid)
{
ApplicationUser myuser = new ApplicationUser();
model.CreatedOn = DateTime.Now;
model.IsActive = true;
myuser.PatientID = Pat_id;
if (ModelState.IsValid)
{
var user = model.GetUser();
db.Patients.Add(pt);
db.SaveChanges();
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
var idManager = new IdentityManager();
idManager.AddUserToRole(user.Id, model.User_type);
//await db.SaveChangesAsync();
await SignInAsync(user, isPersistent: false);
return RedirectToAction("Index", "Home");
}
else
{
AddErrors(result);
}
}
return RedirectToAction("Index", "Home");
}
// If we got this far, something failed, redisplay form
return View();
}
公共异步任务
注意:数据保存在患者表中,但不保存在应用程序用户表中,因为应用程序用户未获取“PatientID”,因此数据库中发生冲突
我希望这一点非常清楚,并且不容易解决:(在应用程序用户模型中,写下这一点:
public class ApplicationUser : IdentityUser
{
public DateTime BirthDate { get; set; }
public string User_type { get; set; }
public DateTime CreatedOn { get; set; }
public Enums.Sex Gender { get; set; }
public bool IsActive { get; set; }
[ForeignKey("PatientID")]
public virtual Patient Patients{ get; set; }
}
我认为它会起作用。感谢您的回复,但在患者表中插入相同的问题记录,而不是在应用程序中用户:(您将数据插入到患者表中。并且您希望将PatientID作为外键插入ApplicationUser表中。我说的对吗?您会应用编辑的代码吗?为什么在Patient类中使用此行?public ICollection ApplicationUser{get;set;}
好的,我删除了它,但遇到了同样的问题。请帮助我解决这个问题。错误意味着,无论您试图将哪个值作为PatientID插入ApplicationUser,该值都不存在于PatientID表的PatientID列中。因此,您需要调试代码,并检查代码是否正确获取PatientID