I’m building an ASP.NET MVC 3 site using the code-first Entity Framework 4 approach. I have one object in my model, Problem, that contains a child collection of another model object, ProblemRating. Currently I have the Problem model set up as follows:
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; }
}
The ProblemRating class is pretty simple:
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; }
}
The boilerplate code in the Create method of the controller isn’t reporting a valid model when I fill out the fields and click “Create”:
if (ModelState.IsValid)
{
db.ProblemModels.Add(problemmodel);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(problemmodel);
What is the correct way to handle child collections of a model inside another model class? I’m not 100% sure about the usage of the ForeignKey attribute either, am I using that correctly?
Thanks!
Change your ProblemModel class as follows
…and in you ProblemRating vlass do the following
The wizardary of EF code first (handy naming assumptions) will do the rest for you.
Check this out
http://weblogs.asp.net/scottgu/archive/2010/07/16/code-first-development-with-entity-framework-4.aspx
You can also remove the key attributes on your Problem Id column