Remove the virtual from your Attachments navigation property to prevent lazy loading:
public ICollection<Attachment> Attachments { get; set; }
First method: issue two separate queries: one for messages, one for attachments and let the interdependence do the rest:
List<Post> postsWithAuthoredAttachments = _context.Posts .Include(p => p.Comments) .Include(p => p.PostAuthor) .Where(p => p.PostAuthor.Id == postAuthorId) .ToList(); List<Attachment> filteredAttachments = _context.Attachments .Where(a => a.Post.PostAuthor.Id == postAuthorId) .Where(a => a.Owner is Author) .ToList()
Locking links means you can access these filtered attachments through the Post navigation property
The second method: one query to the database, followed by a query in memory:
var query = _context.Posts .Include(p => p.Comments) .Include(p => p.PostAuthor) .Where(p => p.PostAuthor.Id == postAuthorId) .Select(p => new { Post = p, AuthoredAttachments = p.Attachments Where(a => a.Owner is Author) } );
I would just use an anonymous type here
var postsWithAuthoredAttachments = query.ToList()
or I would create a ViewModel class to avoid an anonymous type:
List<MyDisplayTemplate> postsWithAuthoredAttachments =
Or, if you really want to expand the messages:
List<Post> postsWithAuthoredAttachments = query.//you could "inline" this variable .AsEnumerable() //force the database query to run as is - pulling data into memory .Select(p => p) //unwrap the Posts from the in-memory results .ToList()
Colin source share