我有一个代码优先数据库。引起我问题的表格是
public class Deadline
{
public Deadline() { }
public Deadline(Year year)
{
this.Year = year;
}
public Guid Id { get; set; }
[Required]
public Year Year { get; set; }
[Required]
[DataType(DataType.Date)]
[DataAnnotationsExtensions.Date]
public DateTime From { get; set; }
[Required]
[DataType(DataType.Date)]
[DataAnnotationsExtensions.Date]
public DateTime To { get; set; }
}
public class Year
{
public Year(Int32 value) { this.Value = value; }
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }
[Required]
[Display(Name="Year")]
[DataAnnotationsExtensions.Year]
public Int32 Value { get; set; }
public virtual Deadline Deadline { get; set; }
}
我今年有一个控制器,它有 create get 方法
public ActionResult Create()
{
ViewBag.Id = new SelectList(db.Deadline, "Id", "Id");
var Year = new Year(db.Year.OrderByDescending(x => x.Value).FirstOrDefault().Value + 1);
Year.Deadline = new Deadline(Year);
return View(Year);
}
和 post 方法
[HttpPost]
public ActionResult Create(Year year)
{
if (ModelState.IsValid)
{
if (db.Year.Select(x => x.Value).Contains(year.Value))
{
ModelState.AddModelError("AlreadyExists", "That year has already been added to the database, please edit instead");
return View(year);
}
db.Year.Add(year);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(year);
}
每当我尝试创建一个新的年份(已设置年份值和截止日期)时,它都会返回帖子并且模型状态无效并说
年份字段是必需的。
我已经检查并在 post 方法 year.Deadline.Year 确实为空,我想知道的是为什么(以及我如何解决这个问题)它一直让我发疯,甚至把
@{ Model.Deadline.Year = Model; }
在视图中什么也没做。
编辑以下作品
using (ProjectSelectionAndAllocation.Models.DatabaseContext Context = new Models.DatabaseContext())
{
var h = new Models.Year(1001);
h.Deadline = new Models.Deadline(h);
Context.Year.Add(h);
Context.SaveChanges();
}