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());
}
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
If you have a foreign key between Comments and Projects you can do something like this
db.ContextOptions.LazyLoadingEnabled = false;
var projects = from p in db.Projects.Include("Comments")
orderby p.TimeAdded descending
select p;
It will load all comments for all projects when you will execute the .ToList(). You'll be able to access the data by the navigate property "Comments" of the project object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With