views:

109

answers:

2

I have a List that includes IQueryAble inside as a property. I'm passing List to my View in MVC project. I iterate through the List using foreach. Inside the foreach:

Albums in type of List

<% foreach(var x in Albums){%>

 <h1><%= x.Title %></h1>
<p><%= x.Photos.Count() %> </p>

<%}%>

Displaying the Title is not an issue, but it throws an error as soon it hits the Count(): "This method is not supported against a materialized query result."

what does this mean? I cannot have collection inside a collection? as soon as I iterate through the collection, the other collection inside that class is not useable anymore.

thanks

A: 

I think you will have to include Photos in your Albums query. Something like.

var Albums = from a in context.Ablums.Include("Photos") select a;
Ralph Shillington
the collection of foto is already included, if I debug it I can see it in my controller, but once I iterate through the albums and try to count the photos inside the album (inside the iteration), it throw that error.
dritterweg
+1  A: 

Use a presentation model:

public class AlbumPresentation
{
    public string Title { get; set; }
    public int PhotoCount { get; set; }
}

Then project onto the model in your controller:

var model = (from a in Context.Albums // or, more likely, via a repository
             select new AlbumPresentation
             {
                 Title = a.Title,
                 PhotoCount = a.Photos.Count()
             }).ToList();
return View(model);

The type of your View is now ViewPage<IEnumerable<AlbumPresentation>>.

Note that unlike using eager loading (Include()), you are no longer required to load all of the Photo records from the database just to get the count. You can load that information if you need it, but only if you need it.

Craig Stuntz
I think this would work, but I need to change the underlaying model. I use presentation model. In my presentation model I have thispublic class AlbumViewModel{ public List<Album> MyAlbums {get;set:}}inside each of Album there are photos. Looks like I cannot do any Linq extension operation from inside a collection which I'm iterating. Just don't see the reason why.
dritterweg
You only need to change your model enough to add one `int` property to it (for the count). As for why, I think there's more code you're not showing us here. "Materialized query result?" Your tags say EF, but that sounds like L2S to me.
Craig Stuntz