Not loading a child property into memory

entity-framework-core

Question

I have the following Entities on Entity Framework Core 2.2:

public class Post {
  public Int32 Id { get; set; }
  public string Type { get; set; }
  public virtual Collection<File> Files { get; set; }
}

public class File {
  public Int32 Id { get; set; }
  public Int32 PostId { get; set; }
  public String Name { get; set; }
  public Byte[] Content { get; set; }
  public virtual Post Post { get; set; }
}

I need to get the list of files Ids and Names of a Post without loading their Content into Memory.

  IQueryable<Post> posts = _context.Posts.AsNoTracking();

  posts = posts.Include(x => x.File);

  var files = await posts
    .Where(x => x.Type == "design")
    // Remaining Query

I think the moment I use Include the files will be loaded into memory. No?

What is the correct way to get a list of Posts' Files Ids and Names without loading their Content into Memory?

1
1
1/21/2019 5:50:29 PM

Accepted Answer

I need to get the list of files Ids and Names of a Post without loading their Content into Memory.

What is the correct way to get a list of Posts' Files Ids and Names without loading their Content into Memory?

Once you said you want to get a Post and then said you want to get a list of Post.

So to get a Post with its files (only Id and Name) you can write your query as follows:

var post = await _context.Posts.Where(yourCondition).Select(p => new
                {
                   p.Id,
                   p.Type
                   Files = p.Files.Select(f => new {f.Id,f.Name}).ToList()
                }).FirstOrDefaultAsync();

And to get list of Posts with its files (only Id and Name) you can write your query as follows:

var posts = await _context.Posts.Where(yourCondition).Select(p => new
                {
                   p.Id,
                   p.Type
                   Files = p.Files.Select(f => new {f.Id,f.Name}).ToList()
                }).ToListAsync();

Note: If you need strongly typed then can write as follows:

Post post = await _context.Posts.Where(yourCondition).Select(p => new Post
                    {
                       Id = p.Id,
                       Type = p.Type
                       Files = p.Files.Select(f => new File {f.Id,f.Name}).ToList()
                    }).FirstOrDefaultAsync();
1
1/22/2019 5:56:50 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow