【发布时间】:2020-02-02 15:44:11
【问题描述】:
我正在使用 EF Core 使用 ASP.NET Core 3.0 创建我的第一个项目。创建用户(患者)时,我希望他们能够在创建视图中分别输入他们的名字和姓氏,这些将分别保存在我的数据库中的 FirstName 和 LastName 列中。但是,我希望将这两个字段合并并存储在另一个名为 FullName 的列中,以便我可以使用它来搜索用户。有没有一种简单的方法可以做到这一点?
我已经尝试使用下面的代码,但我得到一个未处理的异常 -
"SqlException: 无法将值 NULL 插入到列 'FullName' 中, 表'WebPMR.dbo.Patient';列不允许空值。插入失败。 声明已终止”
型号:
public class Patient
{
public int Id { get; set; }
[Display(Name = "Title")]
public int TitleId { get; set; }
[Required]
[Display(Name = "First Name")]
[StringLength(25, MinimumLength = 1, ErrorMessage = "First Name must be 1-25 characters long")]
public string FirstName { get; set; }
[Required]
[Display(Name = "Last Name")]
[StringLength(50, MinimumLength = 1, ErrorMessage = "Last Name must be 1-50 characters long")]
public string LastName { get; set; }
private string _fullName;
public string FullName
{
get => _fullName;
set => _fullName = FirstName + " " + LastName;
}
}
控制器:
// GET: Create
public IActionResult Create()
{
return View();
}
// POST:Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("Id,FirstName,LastName")] Patient patient)
{
if (ModelState.IsValid)
{
_context.Add(patient);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
ViewData["TitleId"] = new SelectList(_context.Title, "Id", "Description", patient.TitleId);
return View(patient);
}
【问题讨论】:
标签: sql-server asp.net-mvc entity-framework asp.net-core