Bacon
Bacon

Reputation: 823

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.

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

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

Upvotes: 0

Views: 420

Answers (1)

Joe
Joe

Reputation: 26

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.

Upvotes: 1

Related Questions