2013-11-24 45 views
0

問題:我可以保存到自引用集合,但實體框架在保存到數據庫後不會在集合中顯示它們。實體框架 - 懶加載自引用集合

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

feats.Include( 「PrerequisiteFeats」)的SingleOrDefault(X => x.Id == 2)

這將基本上查詢兩者專長和前提專長在相同的查詢。它將2個獨立的查詢合併爲一個。

+0

這個伎倆。你的大腦比我的聰明。 – Jeff