EF4 LINQ Ordering Parent and all child collections with Eager Loading (.Include())

后端 未结 1 612
走了就别回头了
走了就别回头了 2020-12-03 09:22

I am doing hierarchical data binding on a grid, and I need to have the database server perform the sorting on my objects. I can easily sort the parent collection, but I can

相关标签:
1条回答
  • 2020-12-03 10:05

    If you need to have Ordering or Filtering on inner navigation properties (e.g. Models) then you cannot eager load them using Include method anymore. Instead, you can use EntityCollection<TEntity>.CreateSourceQuery Method like this:

    List years = db.Years.OrderBy("it.Name").ToList();
    foreach(year in years) 
    {
        var makesQuery = year.Makes.CreateSourceQuery().OrderBy(m => m.Name);
        year.Makes.Attach(makesQuery);  
    
        foreach(make in year.Makes) 
        {
            var modelsQuery = make.Models.CreateSourceQuery().OrderBy(m => m.Name);
            make.Models.Attach(modelsQuery);
    
            foreach(model in make.Models) 
            {
                var colQuery = model.Colors.CreateSourceQuery().OrderBy(c => c.Name);
                model.Models.Attach(colQuery);        
            }
        }
    }
    

    This way, the years object will be constructed with having all of its navigation properties ordered.

    0 讨论(0)
提交回复
热议问题