Netah
Netah

Reputation: 245

EF5 code first querying ICollection from MVC4 view

I did not find the answer so i ask the question... Sorry to bother.

I use code first with an Article class looking like

public class Article
{
    ...
    public virtual ICollection<Photos> Images { get; set; }
    ...
}
public class Photo
{
   ...
   public string Location {get;set;}  //can be home, work or anything
   ...
}

Now, in the HomeController, i get all articles and do

if(articles.Any())
{
      ViewBag.Articles = articles;
}

And then, in the view

foreach(var article in ViewBag.Articles)
{
     ... Do things working great here but...
}

All of that works great. What I want to do is getting ONE Image with location=="home" (for example) from the ICollection for each article. Trying to do that i get different errors in french who says things like i "can not do a request of type dynamic on an other dynamic", "a datareader is open yet" or "dbContext is closed".

Thank you for any help.

Upvotes: 0

Views: 498

Answers (1)

Cam
Cam

Reputation: 378

I think ViewBag.Articles in the view did not contain Photo entities. When you tried to access Photos, the context was closed and caused an error.

My suggestion would be:

Call Include in your controller to early-load Photo entities.

http://msdn.microsoft.com/en-us/library/bb738708.aspx

Then, call ToList when you assign Articles:

ViewBag.Articles = articles.ToList();

Besides the point, it is good practice to use ViewModel, instead of putting data objects into ViewBag. Good luck.

Upvotes: 1

Related Questions