I have recently started using generic repository pattern in my new application, I have been following this guide by Chris Pratt Truly Generic Repository. I am eagerly loading my navigation properties in my GetQueryable Method like this
if (includeProperties != null)
{
foreach (var includeProperty in includeProperties.Split
(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
{
query = query.Include(includeProperty);
}
}
else
{
foreach (var property in context.Model.FindEntityType(typeof(TEntity)).GetNavigations())
query = query.Include(property.Name);
}
Now the first level of navigation properties are loading fine but if I have a navigation property inside a navigation property i.e. at second level it is not being loaded hence returns null,
public partial class Project : Entity<int>
{
public Project()
{
this.UserProjects = new HashSet<UserProject>();
}
[Required]
public string Title { get; set; }
public virtual ICollection<UserProject> UserProjects { get; set; }
}
public class UserProject : Entity<int>
{
public int UserId { get; set; }
public virtual User User { get; set; }
public int ProjectId { get; set; }
public virtual Project Project { get; set; }
}
public class User : IdentityUser<int>
{
public User()
{
this.UserProjects = new HashSet<UserProject>();
}
public Photo Photo { get; set; }
public virtual ICollection<UserProject> UserProjects { get; set; }
}
Here when I query Projects the UserProjects are populated correctly and inside UpserProjects Project is also getting populated but User is null although UserProject has userId.