简体   繁体   中英

Entity Framework - Lazy Loading Self Referencing Collections

Problem: I'm able to save to a self referencing collection but Entity Framework does not show them in the collection after saving to the database.

查询ID为22的Feat

EF生成的多对多表中ID为22的壮举

Feat ID 22,与之无关

Desired: Access entities in the collection by {entity}.{collection}.{query()};

Entity:

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

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

Context:

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

feats.Include("PrerequisiteFeats").SingleOrDefault(x => x.Id == 2)

This will basically query both Feats and Prerequisite Feats in the same query. It's combining 2 seperate queries into one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM