Home > Back-end >  Entity Framework loading some, none or all navigation properties dynamically
Entity Framework loading some, none or all navigation properties dynamically

Time:04-07

Looking at this documentation I can see that you can load multiple navigation entities using the following syntax:

using (var context = new DbContext())
{
    var userDocs = context.UserDocuments
        .Include(userDoc => userDoc.Role.User)            
        .ToList();
}

This will give me Role and User navigation properties hung off my UserDocument object, however if I want to use the string overload of Include, how might I construct the code to handle multiple includes?

This does not work:

return await ctx.UserDocuments.Where(x => x.UserId == userId)
.Include("Role.User").ToList();

I am trying to do it this way as my methods may want some, all or no navigation properties returned depending on the calling code. My intention is to add a string array to the repository method which will build any required navigation properties accordingly. If this is the wrong approach, does anyone have another recommendation, I'm wondering if lazy loading would be a more elegant solution...?

Edit

This is the Entity which has nav props:

public partial class UserDocument
{
  public int Id { get; set; }
  public Guid UserId { get; set; }
  public int RoleId { get; set; }
  public int AccountId { get; set; }
     
  public virtual Role Role { get; set; } = null!;
  public virtual User User { get; set; } = null!;
}

CodePudding user response:

If you're using the Include(String) method, you don't need to include the lambda to specify the property path.

Instead of doing .Include(x => "Role.User"), try .Include("Role.User")

CodePudding user response:

First of all, you must told us what is "Role.User"? We cannot answer you if we don't know excactly what you wrote.

So, now we are know that are two differents entities you can do this one

var userDocs = await context.UserDocuments
    .Include(x => x.Role)
    .ThenInclude(x => x.User) 
    .ToListAsync();

I hope this one helps you. :)

CodePudding user response:

I think you are looking for something like this:

public async Task<List<UserDocument>> MyMethod(List<string> propertiesToInclude)
{
    IQueryable<UserDocument> currentQuery = _context.UserDocuments.Where(x => x.UserId == userId);
    
    foreach(var property in propertiesToInclude)
    {
        currentQuery = currentQuery.Include(property);
    }
    return await currentQuery.ToListAsync();
}
  • Related