N
N
NameOf Var2020-03-16 16:31:38
.NET
NameOf Var, 2020-03-16 16:31:38

How to load nested properties through EF Core using Expression?

Such a situation: there is a ListAsync method in the repository method, approximately implemented like this:

public virtual async Task<IEnumerable<TEntity>> ListAsync(
            params Expression<Func<TEntity, object>>[] includeProperties)
        {
            IQueryable<TEntity> query = this.QueryableEntities;
 
            if (includeProperties != null)
            {
                foreach (Expression<Func<TEntity, object>> includeProperty in includeProperties)
                {
                    query = query.Include(includeProperty);
                }
            }
 
            return await query.AsNoTracking().ToListAsync();
        }


The includeProperties parameter tells which nested properties to load as well. I have three more entities:
class Image
{
        public Guid ImageGuid { get; set; }
 
        public List<ImageTag> ImageTags { get; set; }
}
 
class ImageTag
{
        public Guid ImageGuid { get; set; }
 
        public Image Image { get; set; }
 
        public int TagId { get; set; }
 
        public Tag Tag { get; set; }
}
 
class Tag
{
        public int TagId { get; set; }
 
        public string Name { get; set; }
 
        public List<ImageTag> ImageTags { get; set; }
}


Now I want to load a list of all Image. Through the ImageRepository I write the following code:
imageRepository.ListAsync(
   (img) => img.ImageTags.Select(t => t.Tags));


But this implementation throws an exception: Lambda expression used inside Include is not valid. Can you please tell me how to correctly implement the loading of nested properties without ThenInclude in EF Core?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question