【发布时间】:2011-10-02 07:45:45
【问题描述】:
我正在使用代码优先的 Entity Framework 4 方法构建一个 ASP.NET MVC 3 站点。我的模型中有一个对象,Problem,它包含另一个模型对象 ProblemRating 的子集合。目前我的问题模型设置如下:
public class ProblemModel
{
[Key]
[Required]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ProblemId { get; set; }
[Display(Name = "Creator")]
[Required]
public string UserName { get; set; }
[Required]
public string Title { get; set; }
[Required]
public string ProblemDescription { get; set; }
[Required]
public string InputDescription { get; set; }
[Required]
public string InputSample { get; set; }
[Required]
public string OutputDescription { get; set; }
[Required]
public string OutputSample { get; set; }
public virtual IEnumerable<ProblemRatingModel> Ratings { get; set; }
public DateTime CreatedDate { get; set; }
public DateTime LastModifiedDate { get; set; }
}
ProblemRating 类非常简单:
public class ProblemRatingModel
{
[ForeignKey("AssociatedProblem")]
public int AssociatedProblemId { get; set; }
public ProblemModel AssociatedProblem { get; set; }
public string UserName { get; set; }
public decimal Rating { get; set; }
}
当我填写字段并单击“创建”时,控制器的 Create 方法中的样板代码未报告有效模型:
if (ModelState.IsValid)
{
db.ProblemModels.Add(problemmodel);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(problemmodel);
在另一个模型类中处理模型的子集合的正确方法是什么?我也不是 100% 确定 ForeignKey 属性的用法,我正确使用了吗?
谢谢!
【问题讨论】:
标签: asp.net-mvc asp.net-mvc-3 entity-framework