I'm doing MVC 3 Web Application and have weird problem. Here is some code:
Model declaration:
public class Project
{
public int ID { get; set; }
[Required(ErrorMessage = "Write a title.")]
public string Title { get; set; }
public DateTime TimeAdded { get; set; }
[Required(ErrorMessage = "Write some description.")]
[MaxLength(int.MaxValue)]
public string Content { get; set; }
public ICollection<Comment> Comments { get; set; }
}
public class Comment
{
public int ID { get; set; }
[Required()]
public int ProjectID { get; set; }
public DateTime TimeAdded { get; set; }
[Required()]
public string Text { get; set; }
public Project project { get; set; }
}
Controller:
public class HomeController : Controller
{
dataDBContext db = new dataDBContext();
//
// GET: /Home
public ActionResult Index()
{
var comments = from c in db.Comments
select c;
var projects = from p in db.Projects
orderby p.TimeAdded descending
select p;
return View(projects.ToList());
}
- When I run project Comments are not visible on my view.
- I'm setting a breakpoint just after both linq queries, debugging and checking "project" variable fields Comments, they are not populated. Then I'm checking "comments" variable, it has some data. Again checking "project" variable and SOMEHOW fields Comments are populated and finally Comments appears on website. If I won't set breakpoint and check if variable "comments" is populated they won't appear on website. (I hope this is understandable)
I found simple workaround:
public ActionResult Index() { var projects = from p in db.Projects orderby p.TimeAdded descending select p; foreach (var p in projects) { var comments = from c in db.Comments where c.ProjectID == p.ID select c; p.Comments = comments.ToList(); } return View(projects.ToList()); }but it looks (according to point 2) that this can be automatically populated SOMEHOW :)
Is there any way to do it?
Another tries based on given answers:
public class HomeController : Controller
{
dataDBContext db;
public HomeController()
{
db = new dataDBContext();
db.Configuration.LazyLoadingEnabled = false;
}
//
// GET: /Home
public ActionResult Index()
{
var projects = from p in db.Projects
orderby p.TimeAdded descending
select p;
return View(projects.ToList());
}
I have foreign key. I added LazyLoadingEnabled. There is project.ToList() and it doesn't work.
Based on second answer I have done something like that:
public class HomeController : Controller
{
dataDBContext db;
public HomeController()
{
db = new dataDBContext();
}
//
// GET: /Home
public ActionResult Index()
{
var projects = from p in db.Projects
orderby p.TimeAdded descending
select p;
var comments = from c in db.Comments
select c;
List<Comment> l = comments.ToList();
return View(projects.ToList());
}
I have added just comments.ToList() and it is working. But I'm not sure if it is right solution. Probably better than my workaround (point 3). Any suggestions?
Thanks