2017-02-01 11 views
0

Когда я вытягиваю объект MyList через EF, родительский элемент связан правильно, но коллекция Children всегда равна null. Не уверен, что я делаю неправильно, почти каждая статья показывает, чтобы сделать это таким образом.Родительский/дочерний элемент с дочерней коллекцией EF6 всегда null

Database

CREATE TABLE [dbo].[MyList] (
    [MyListId]  BIGINT   IDENTITY (1, 1) NOT NULL, 
    [ParentMyListId] BIGINT NULL, 
    CONSTRAINT [PK_MyList] PRIMARY KEY CLUSTERED ([MyListId] ASC) WITH (FILLFACTOR = 90), 
    CONSTRAINT [FK_MyList_MyList_MyListId] FOREIGN KEY (ParentMyListId) REFERENCES MyList(MyListId) 
); 

Модель

public class MyList 
{ 
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)] 
    public long MyListId { get; set; } 
    public long? ParentMyListId { get; set; } 

    [ForeignKey("ParentMyListId")] 
    public virtual List MyListParent { get; set; } 

    public virtual ICollection<MyList> MyListChildren { get; set; } 
} 

DbContext

public class MyContext : DbContext 
{ 
    public MyContext() : base(Properties.Settings.Default.DbContext) 
    { 
     Configuration.LazyLoadingEnabled = false; 
    } 

    public DbSet<MyList> MyLists { get; set; } 

    protected override void OnModelCreating(DbModelBuilder modelBuilder) 
    { 
     modelBuilder.Entity<MyList>() 
     .ToTable("MyList", "dbo") 
     .HasOptional(x => x.MyListParent) 
     .WithMany(x => x.MyListChildren) 
     .HasForeignKey(x => x.ParentMyListId) 
     .WillCascadeOnDelete(false); 
    } 

    base.OnModelCreating(modelBuilder); 
} 
+0

включена отложенная загрузка? –

+1

В качестве альтернативы я рекомендую использовать оператор 'nameof' вместо C#, а не hardcoding строку' 'ParentMyListId'', поэтому вы должны поставить' [ForeignKey (nameof (MyList.ParentMyListId)) '- для дополнительной безопасности времени сборки. – Dai

ответ

1
Hi I tried with same structure in EF 6.1.3 version and it worked like charm .I added image of output and data present in db .The only thing that might stoped working if you disable loading in configuration . I hope it work for you please try my sample code . 

    // Your entity class I added name property to show you the results 
    public class MyList 
    { 
     [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)] 
     public long MyListId { get; set; } 
     public long? ParentMyListId { get; set; } 

     public string Name { get; set; } 

     [ForeignKey("ParentMyListId")] 
     public virtual MyList MyListParent { get; set; } 

     public virtual ICollection<MyList> MyListChildren { get; set; } 
    }  
    // DBContext please note no configuration properties set just default constructor you need t check here if you have set soemthing here 
     public class TestContext : DbContext 
     { 
      public TestContext() 
       : base("name=TestConnection") 
      { 
      }    

      protected override void OnModelCreating(DbModelBuilder modelBuilder) 
      { 
       modelBuilder.Entity<MyList>() 
       .ToTable("MyList", "dbo") 
       .HasOptional(x => x.MyListParent) 
       .WithMany(x => x.MyListChildren) 
       .HasForeignKey(x => x.ParentMyListId) 
       .WillCascadeOnDelete(false); 

      } 

      public virtual DbSet<MyList> Lists { get; set; } 
     } 

// consile приложение, чтобы показать результат

static void Main(string[] args) 
    { 
     using (var ctx = new TestContext()) 
     { 

      // for testing to see al working 
      //this is important to read the entity first . 
      var parent = ctx.Lists.ToList(); 

      foreach (var p in parent) 
      { 
       foreach (var child in p.MyListChildren) 
       { 
        Console.WriteLine(string.Format(@"Parent Name {0} has child with name {1}", p.Name, child.Name)); 
       } 
      } 

     } 

     Console.ReadLine(); 
    } 

// выход приложения й данных в базе данных ...

enter image description here

+0

Я, наверное, буду больше разбираться в проблемах. Не знаю, почему мой не работает. – user3953989

+1

plz поделиться своим классом dbcontext –

+0

Обновить OP, чтобы включить dbcontext – user3953989