【发布时间】:2021-12-29 11:18:30
【问题描述】:
我正在使用 mvc .net core (.net 6.0) 创建一个链接到数据库的应用程序,但我遇到了一个问题: 我搭建了一个控制器及其视图(创建、编辑...),但是当我尝试创建一个对象以使用实体框架发送到 db 时,DateOnly 类型的字段将不起作用并为我尝试的所有日期输入此日期写:292269055-12-03(这似乎是最大值?)。 出于兼容性原因,我需要使用 DateOnly 类型,因为数据库有日期字段(我在这里找到了此信息 https://www.npgsql.org/doc/types/datetime.html,如果我尝试使用 datetime,它就不起作用)。
有我的代码: 查看:
<div class="form-group">
<label asp-for="BirthDay" class="control-label"></label>
<input asp-for="BirthDayUI" class="form-control" type="date"/>
<span asp-validation-for="BirthDay" class="text-danger"></span>
</div>
控制器(自动生成):
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("Id,Name,FirstName,BirthDay,Email,MobilePhone,LandLinePhone,PostalCity,PostalCode,PostalAdress,Gender,MedicalCertificate,MedicalCertificateStart,MedicalCertificateEnd,ProfilePicture")] Member member)
{
if (ModelState.IsValid)
{
_context.Add(member);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(member);
}
最后,我试图摆弄这个的模型:
[Required]
public DateOnly BirthDay { get; set; }
[NotMapped]
public DateTime BirthDayUI
{
get => BirthDay.ToDateTime(new TimeOnly());
set => BirthDay = DateOnly.FromDateTime(value);
}
getter 可以完美运行,但 setter 不行,我不知道我必须更改什么。
谢谢你帮助我
【问题讨论】:
标签: c# .net asp.net-mvc entity-framework