查询时,没有包含导航属性相关联的实体。这是什么情况?
根据某书教程例子写的代码:
实体:
public class PictureCategory
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int CategoryId { get; private set; }
public string Name { get; set; }
public int? ParentCategoryId { get; private set; }
[ForeignKey("ParentCategoryId")]
public PictureCategory ParentCategory { get; set; }
public List<PictureCategory> Subcategories { get; set; }
public PictureCategory()
{
Subcategories = new List<PictureCategory>();
}
}
关系:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<PictureCategory>()
.HasMany(cat => cat.Subcategories)
.WithOptional(cat => cat.ParentCategory);
}
运行:
public static void Run(){
using (var context = new EF6Context())
{
context.Configuration.LazyLoadingEnabled = true;
var roots = context.PictureCategories.Where(c => c.CategoryId ==1).ToList();
roots.ForEach(root => Print(root, 0));
}
}
public static void Print(PictureCategory cat, int level)
{
StringBuilder sb = new StringBuilder();
Console.WriteLine("{0}{1}", sb.Append(' ', level).ToString(), cat.Name);
cat.Subcategories.ForEach(child => Print(child, level + 1));
}