I have a User to User Role many-to-many relationship set up similar to the example here. https://www.learnentityframeworkcore.com/configuration/many-to-many-relationship-configuration
However when I try to query the Users it returns the users as expected but the UserRoles(BookCategories in the example) is always null. Do I need to use Include() and ThenInclude()? I tried using each but that doesn't seem to work, either.
I've tried something like this
var users = _context.TFCpUserTests.Include(e =>
e.TFCpUserRoleTests).ThenInclude(e => e.TFCpRoleTest);
but I can't use ThenInclude() for some reason. Here's the models I'm using
public class TFCpRoleTest
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<TFCpUserRoleTest> TFCpUserRoleTests { get; set; }
}
public class TFCpUserTest
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Username { get; set; }
public string Email { get; set; }
public byte[] PasswordHash { get; set; }
public byte[] PasswordSalt { get; set; }
public virtual ICollection<TFCpUserRoleTest> TFCpUserRoleTests { get; set; }
}
public class TFCpUserRoleTest
{
public int UserId { get; set; }
public virtual TFCpUserTest TFCpUserTest { get; set; }
public int RoleId { get; set; }
public virtual TFCpRoleTest TFCpRoleTest { get; set; }
}
This is a known Intellisense issue with the ThenInclude
overload for collection type navigation properties, tracked by the Completion missing members of lambda parameter in fault tolerance case #8237 Roslyn GitHub issue.
Until it gets fixed, simply type the name of the property and it will compile successfully and work as expected.
.ThenInclude(mu => mu.ParseSubTrees)
Update: Now it's even specifically mentioned in the Including multiple levels section of the EF Core documentation:
Note
Current versions of Visual Studio offer incorrect code completion options and can cause correct expressions to be flagged with syntax errors when using the
ThenInclude
method after a collection navigation property. This is a symptom of an IntelliSense bug tracked at https://github.com/dotnet/roslyn/issues/8237. It is safe to ignore these spurious syntax errors as long as the code is correct and can be compiled successfully.