我最近开始在新应用程序中使用通用存储库模式,我一直遵循Chris Pratt Truly Generic Repository的指南。我急切地将导航属性加载到这样的GetQueryable方法中
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);
}
现在,第一级导航属性可以很好地加载,但是如果我在导航属性中具有导航属性,即第二级没有被加载,则返回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; }
}
在这里,当我查询项目时,正确填充了UserProject,并且在UpserProjects内部也填充了Project,但是尽管UserProject具有userId,但User为null。