使用 EF 将表的主键作为外键映射到 AspNetUser 表
本文关键字:映射 AspNetUser EF 使用 | 更新日期: 2023-09-27 18:36:55
我正在尝试创建一个应用程序,其中我有一个 5 度的表格,用户可以从下拉列表中选择一个度数。提交后,所选度数的 id 应该作为外键保存在 AspNetUser 表中,但这在我的代码中没有发生。相反,每当我注册新用户时,degree_id列都会留空或"NULL"。我正在使用实体框架来构建我的应用程序。
/* This is my Account/Register Controller */
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser
{
UserName = model.Email,
Email = model.Email,
FirstName = model.FirstName,
LastName = model.LastName,
StudentId = model.StudentId,
Degree = model.Degree,
UserProfileInfo = new UserProfileInfo
{
CurrentCourses = model.CurrentCourse,
TakenCourses = model.TakenCourse,
PlannedCourses = model.PlannedCourse,
appointment = model.Appointment,
}
};
我的寄存器视图模型中有这行学位代码
[Display(Name = "Degree")]
public Degree Degree { get; set; }
IdentityModels.cs 在 ApplicationUser : identityUser class 下有这样一行代码:
public class ApplicationUser : IdentityUser
{
.
.
.
public virtual Degree Degree { get; set; }
.
.
.
.
.
}
我的寄存器视图如下所示:
<div class="form-group">
@Html.LabelFor(model => model.Degree, "Degree", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("Degrees", new SelectList(ViewBag.Degrees, "Id", "Title"), "-- Select Degree --", htmlAttributes: new { @class = "form-control" })
</div>
否,值未回发
根据您的评论,下拉列表未正确配置。这就是您无法检索已发布值的原因。
看看这个例子——
控制器
public class YourController : Controller
{
public ActionResult Index()
{
var model = new RegisterViewModel();
model.Degrees = new List<SelectListItem>
{
new SelectListItem { Text = "One", Value = "1"},
new SelectListItem { Text = "Two", Value = "2"},
new SelectListItem { Text = "Three", Value = "3"},
};
return View(model);
}
[HttpPost]
public ActionResult Index(RegisterViewModel model)
{
string degreeId = model.SelectedDegreeId;
}
}
型
public class RegisterViewModel
{
public string SelectedDegreeId { get; set; }
public IEnumerable<SelectListItem> Degrees { get; set; }
}
视图
@using (Html.BeginForm())
{
@Html.DropDownListFor(x => x.SelectedDegreeId, Model.Degrees)
<button type="submit">Submit</button>
}