0

My table relations:

Categories has many Posts has many PostImages

I want to retrieve Categories>LastPost>FirstPostImage. And I tried something like following:

var categories = entity.Categories
                 .Where(x => x.PositionId == 2)
                 .Include(x => x.Posts.Last())
                 .Include(x => x.Posts.Last().PostImages.First())
                 .Take(5)
                 .ToList();

Question: Is there an elegant way to achive this? Is there commonly usage of eager loading for nested relational tables?

Erik Funkenbusch
  • 92,674
  • 28
  • 195
  • 291
AliRıza Adıyahşi
  • 15,658
  • 24
  • 115
  • 197

2 Answers2

2

EF doens't support queries on included tables, but you can use a Select clause for sub-queries:

var categories = entity.Categories
  .Where(x => x.PositionId == 2)
  .Select( x => new {
    Category = x,
    LastPost = x.Posts.Last(),
    FirstImage = x.Posts.Last().PostImages.First(),
  })
  .Take(5)
  .ToList();

You will end up with a List<anonymous> but it will get ( just ) the data you need.

Nick Butler
  • 24,045
  • 4
  • 49
  • 70
1

I would recommend you to use Data transfer Objects(DTO). Just create new class:

public class CategoriesPostPostImagesDto
{
     public Categories Category {get;set;}
     public Posts Post {get;set;}
     public PostImages PostImage {get;set;}

}

And then select data to it from DB.

List<CategoriesPostPostImagesDto> data = entity.Categories
  .Where(x => x.PositionId == 2)
  .Select( x => new CategoriesPostPostImagesDto(){
    Category = x,
    Post = x.Posts.Last(),
    PostImage = x.Posts.Last().PostImages.First(),
  })
  .Take(5)
  .ToList();

There is a lot of information about the DTO in the internet:

like this: ADO.NET EF - populate DataGridView when we have Foreign Key

Community
  • 1
  • 1
Maris
  • 4,608
  • 6
  • 39
  • 68