0

For several pages I use a .Count inside a foreach loop

@model ICollection<Item>
foreach(var item in Model)
{
    @item.Flight.FlightReservations.count
}

Because of lazy loading the EF makes a round trip to the database for this.

Now I want to fix this by using this or linq version: Include("List.Flight.FlightReservations")

Doing this makes loading my dbSet take even longer than those foreach round trips

How can I 'load' parts of only 1 object?

I would like to use context.Items.Single(p => p.id == id).Include(.....) So I only load 1 item fully.

Or any other solutions for this? (A way to force load item.List.item2.List inside controller)

Any suggestions are welcome :) Thanks

EDIT : now using

Where(..).ToDictionary(item => item, item => item.Flight.FlightReservations.Count); Also noticed adding an index to my 'clustered index' table helped a little. Still slow though

var f = _pr.FindBy(duifid);
var result = (from p in f.IngeschrevenVluchten
              select new PrestatieModel
              {
                 Eindpos = p.Eindpositie, 
                 Locatie = p.Vlucht.Locatie.Naam, 
                 AantalInschrijvingen = p.Vlucht.Inschrijvingen.Count(), 
                 Vlucht = p.Vlucht
              });

This query executes very fast, making a IEnumerable<Model>. But still it loads very slow once sent to the view.

return PartialView(result);
nawfal
  • 70,104
  • 56
  • 326
  • 368
  • You probably want to write your EF query so that it calculates the counts separately, without loading all the FlightReservations objects. ToDictionary is a step in the right direction but it gets executed after the data arrive from SQL, you need to load the count *when* the data is being retrieved. – Andrew Savinykh Jan 17 '13 at 04:55
  • Try do it with a join / grouping. http://stackoverflow.com/questions/534690/linq-to-sql-return-anonymous-type – Slappy Jan 17 '13 at 05:41
  • I tried something like your link Slappy,(fast return of results) but it still loads very long on the view. If I add .ToList() , it takes very long to return the result. So it's basicly the same again :/ – user1834463 Jan 17 '13 at 16:30
  • "This query executes very fast.." this is not the fact, CLR prepares for the fetch but never process until you read/iterate the values. Here variable f will be populated only when you start iterating/reading (in the VIEW). http://msdn.microsoft.com/en-us/library/vstudio/9k7k7cf0.aspx – vinodpthmn Jan 17 '13 at 18:36
  • Alright vinodpthmn, I didn't know that :) thanks. Anyway I should create a sqlquerycommand myself. Hoping it will be a lot faster that way – user1834463 Jan 17 '13 at 19:18

0 Answers0