Entity Framework 多对多未加载相关实体

Entity Framework Many-to-Many not loading related entities

我必须 2 个实体 类 具有通过 FluentAPI 定义的多对多关系。 Entity1 具有包含相关 Entity2 对象的虚拟集合。 Entity2 没有这个集合,因为我不需要它。 我的 类 看起来像这样:

  internal class Franchisee : UserAccount //abstract base class with more properties
  {
        public virtual ICollection<FranchiseOffice> FranchiseOffices { get; set; } 
  }

  internal class FranchiseOffice: Office //abstract base class
  {
        <many properties, but no collection for Franchisee-objects>
  }

多对多关系的配置:

 protected override void OnModelCreating(DbModelBuilder modelBuilder)
 {
            Database.SetInitializer(new MigrateDatabaseToLatestVersion<CoreModel, Migrations.Configuration>());

            //many-to-many relationship with only one navigation property
            modelBuilder.Entity<Franchisee>().HasMany(u => u.FranchiseOffices).WithMany().Map(m =>
            {
                m.MapLeftKey("FranchiseeId");
                m.MapRightKey("FranchiseOfficeId");
                m.ToTable("FranchiseOffices");
            });
  }

有效的方法:保存实体并通过导航将它们链接在一起属性。数据库中的数据看起来不错;映射 table 'FranchiseOffices' 在那里并且充满了数据。

什么不起作用:当我加载 Franchisee 时,集合 'FranchiseOffices' 为 NULL,尽管数据库中存在它的数据。

我能看到的与在线示例的唯一区别是我在两边都使用了继承 类。我尝试明确查询 child-类,但结果是一样的。有什么想法吗?

感谢 Ivan Stoev,我发现了问题:我所有的实体 类 都是 "internal"(而不是默认的 "public")。我想将它们隐藏在库中,因为在将它们交给外部之前我使用了从实体到业务对象的转换。 这使得以下代码成为必要:

  public CoreModel() : base("name=DefaultConnection")
  {
            //manually init the DbSets because they are 'internal' which prevents automatic init
            UserAccounts = Set<UserAccount>();
            Offices = Set<Office>();
   }

由于 many-to-many 关系创建了一个单独的映射 table,因此缺少 table 的显式初始化,这导致 EF 错过了相关实体的延迟加载。由于我不知道如何初始化我无法控制的 table,我只是将所有实体设为 "public",问题就消失了。 另一个解决方案是自己创建映射 table,以便能够保留所有内容 "internal" 并自己初始化它。