实体框架 - 延迟加载自引用集合

时间:2013-11-24 23:17:16

标签: c# .net database entity-framework

问题:我可以保存到自引用集合,但保存到数据库后,Entity Framework不会在集合中显示它们。

Query on Feat with ID of 22

Feat with ID of 22 in many-to-many table generated by EF

Feat ID 22 with nothing associated with it

期望:{entity}.{collection}.{query()};

访问集合中的实体

实体:

class Feat
{
    public Feat()
    {
        PrerequisiteFeats = new HashSet<Feat>();
    }

    public int Id { get; set; }
    // Other properties here
    public virtual ICollection<Feat> PrerequisiteFeats { get; set; }
}

上下文

class PathfinderContext : DbContext
{
    public DbSet<Feat> Feats { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Feat>()
                    .HasMany(feat => feat.PrerequisiteFeats)
                    .WithMany()
                    .Map(m =>
                    {
                        m.MapLeftKey("FeatId");
                        m.MapRightKey("PrerequisiteFeatId");
                        m.ToTable("PrerequisiteFeats");
                    });
    }
} 

1 个答案:

答案 0 :(得分:1)

feats.Include(“PrerequisiteFeats”)。SingleOrDefault(x =&gt; x.Id == 2)

这将基本上查询同一查询中的Feats和Prerequisite Feats。它将2个单独的查询合并为一个。