我有一个包含两个实体的 ASP.NET Core MVC 应用程序:
Employee
和 Task
。这两个实体之间的关系是一对多的。
为员工存储的信息是全名、电子邮件、电话号码、出生日期和月薪。该任务由标题、描述、受让人(分配到该任务的员工)和截止日期组成。
当我要创建员工时,
ModelState
返回错误:
“需要任务”
因为那个错误,我无法创建员工。
[HttpPost]
public async Task<IActionResult> Create([Bind("FullName,Email,PhoneNumber,DateOfBirth,MonthlySalary")] Employee employee)
{
if (ModelState.IsValid)
{
_context.Add(employee);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(employee);
}
public class Employee
{
public int Id { get; set; }
[Required(ErrorMessage = "Enter first and last name")]
[StringLength(30, ErrorMessage = "Maximum 30 characters")]
[Display(Name = "Full name")]
public string FullName { get; set; }
[Required(ErrorMessage = "Enter your email")]
[EmailAddress(ErrorMessage = "Invalid Email address")]
[Display(Name = "Email")]
public string Email { get; set; }
[Required(ErrorMessage = "Enter a phone number")]
[StringLength(20, ErrorMessage = "Maximum 20 characters")]
[Display(Name = "Phone number")]
public string PhoneNumber { get; set; }
[Required(ErrorMessage = "Enter date of birth")]
[DataType(DataType.Date), DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
[Display(Name = "Date of Birth")]
public DateTime DateOfBirth { get; set; }
[Required(ErrorMessage = "Enter the monthly salary")]
[Range(30000,300000, ErrorMessage = "Salary must be in range [30000,300000]")]
[Display(Name = "Monthly salary")]
public int MonthlySalary { get; set; }
public virtual ICollection<Task> Tasks { get; set; }
}
有人知道问题是什么吗?