c# – Lazy Loading无法正常工作,相关实体始终为null

我对EF有问题.

相关实体始终为空.到目前为止我没有得到任何解决方案.

以下是模型:

 public class Categories
 {
    public int ID { get; set; }
    public string Name { get; set; }
    public int AtpID { get; set; }

    public virtual ICollection<SubCategories> SubCategories { get; set; }
 }

 public class SubCategories
 {
    public int ID { get; set; }
    public string Name { get; set; }
    public int CategoryID { get; set; }
    public string LinkToProducts { get; set; }
  }

因此,每个分类都有更多的子类别.
在Seed方法中我填充了数据库,所以我有数据:

var categories = new List<Categories>
        {
        new Categories{Name="Abgasanlage", ID=1},
        new Categories{Name="Elektrik",ID=2},
        new Categories{Name="Filter", ID=3},
        new Categories{Name="Karosserie", ID=4},
        new Categories{Name="Kuhlunkg",ID=5}
        };

        categories.ForEach(s => context.Categories.Add(s));
        context.SaveChanges();

        var subCategories = new List<SubCategories>
        {
        new SubCategories{Name="Montageteile", ID=1, CategoryID=1},
        new SubCategories{Name="Lamdasonde",ID=2, CategoryID=1},
        new SubCategories{Name="Anlasser", ID=3, CategoryID=2},
        new SubCategories{Name="Luftfilter", ID=4, CategoryID = 3},
        new SubCategories{Name="Ohlfilter", ID=5, CategoryID = 3},
        new SubCategories{Name="Sonstige", ID=6, CategoryID = 4},
        new SubCategories{Name="Wasserpumpe", ID=7, CategoryID = 5}
        };

        subCategories.ForEach(s => context.SubCategories.Add(s));
        context.SaveChanges();

看起来似乎evrything是好的,相关实体总是为null,即使使用Include(),也是null.

我试过这种方式:

Models.Categories entity = db.Categories.Where(m => m.ID == 3)
                                   .Include(m => m.SubCategories)
                                   .FirstOrDefault();

但entity.SubCategories始终为null.

with Include也是相关实体为null

var setting = (from s in db.Categories.Include("SubCategories")
                           where s.ID == 3
                           select s).FirstOrDefault();

在我的项目中,我有更多相关的实体,延迟加载工作.

只有这些模型(类别和子类别)我才有问题.
我做错了什么?

最佳答案 您的问题出在SubCategories模型上.您必须解决此问题,如下所示.

注意:使用public virtual Categories Categories {get;组;你没有这样做,当你使用Include或Lazy loading时,EF不知道如何从数据库中获取相关的实体(或导航属性).你还需要将CategoryID更改为CategoriesID.B ‘因为你的模特的名字是类别.

public class SubCategories
 {
    public int ID { get; set; }
    public string Name { get; set; }

    [ForeignKey("CategoriesID")]
    public virtual Categories Categories{ get; set; }//you have to do this
    public int CategoriesID { get; set; }

    public string LinkToProducts { get; set; }
  }
点赞