none
EF的lazyloading没起作用 RRS feed

  • 问题

  • 查询时,没有包含导航属性相关联的实体。这是什么情况?

    根据某书教程例子写的代码:

    实体:

    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));
            }

    2015年3月15日 4:22

答案

  •         [ForeignKey("ParentCategoryId")]
            public PictureCategory ParentCategory { get; set; }
    
            public List<PictureCategory> Subcategories { get; set; }

    修改为:

            [ForeignKey("ParentCategoryId")]
            public virtual PictureCategory ParentCategory { get; set; }
    
            public virtual List<PictureCategory> Subcategories { get; set; }

    2015年3月15日 10:26