2017-08-01 63 views
1

我有以下兩種模式:實體框架實體列表總是空

public class Note 
{ 
    [Key] 
    [DatabaseGenerated(DatabaseGeneratedOption.None)] 
    public string Id { get; private set; } 

    [Required] public string Creator { get; set; } 

    public NoteProfile Profile { get; set; } 

    [Required(AllowEmptyStrings = true)] 
    [DisplayFormat(ConvertEmptyStringToNull = false)] 
    public string Content { get; set; } 

    public static Note Create() 
    { 
     return new Note(); 
    } 

    public Note GenerateId() 
    { 
     this.Id = Guid.NewGuid().ToString(); 
     return this; 
    } 

    public Note Finalize() 
    { 
     this.GenerateId(); 
     this.Profile = NoteProfile.Create().Finalize(); 

     return this; 
    } 
} 

和:

public class User 
{ 
    [Key] 
    [DatabaseGenerated(DatabaseGeneratedOption.None)] 
    public string Id { get; private set; } 

    [ForeignKey("Creator")] 
    [Required] 
    public List<Note> Notes { get; set; } 

    public static User Create() 
    { 
     return new User(); 
    } 

    public User GenerateId() 
    { 
     this.Id = Guid.NewGuid().ToString(); 
     return this; 
    } 

    public User Finalize() 
    { 
     this.GenerateId(); 
     if (this.Notes == null) 
     { 
      this.Notes = new List<Note>(); 
     } 

     return this; 
    } 
} 

我的問題是這樣的:每當創建並保存到數據庫的User一個新實例通過EF,當我稍後從DB返回實體時,Note的列表總是null

我已經設法跟蹤錯誤以下方法:

public static bool AddUser(Models.API.Requests.POST.User post) 
{ 
    var entity = User.Create().Finalize(); 
     List<Note> user1; 
     List<Note> user2; 
     using (var context = new Context()) 
     { 
      context.Users.Add(entity); 
      context.SaveChanges(); 
      user1 = context.Users.First(user => user.Id == entity.Id).Notes; 
     } 

     using (var context = new Context()) 
     { 
      user2 = context.Users.First(user => user.Id == entity.Id).Notes; 
     } 

     return true; 

    return true; 
} 

通過調試器檢查user1user2揭示user1,其所述第一上下文的處置之前創建,是已初始化的List<Note>包含0個項目,而user2(在新的上下文中創建)爲空。

enter image description here

我的背景很簡單:

public class Context : DbContext 
{ 
    public Context(string connectionString) : this(new MySqlConnection(connectionString), false) 
    { 
    } 

    public Context(DbConnection existing, bool contextOwnsConfig) : base(existing, contextOwnsConfig) 
    { 
    } 

    public DbSet<Note> Notes { get; set; } 

    public DbSet<User> Users { get; set; } 
} 

的DB提供程序是MySQL的。檢查EF產生在MySQL Workbench中的表顯示,外鍵確實存在:

enter image description here

加入Note新的實例與他們Creator屬性設置等於我的用戶的Id產生完全相同的結果。

這是怎麼發生的?

+1

代替'公開名單票據{得到;組; }'使用'公共虛擬ICollection 筆記{get;組; }' –

+1

[實體框架加載相關實體](https://msdn.microsoft.com/en-us/data/jj574232.aspx) –

回答

4

您是否已配置lazy loading

如果沒有,您需要Include相關實體明確如下圖所示(Eager loading

你的第一個例子中的作品,因爲這些實體已經在上下文

using (var context = new Context()) 
      { 
       user2 = context 
         .Users 
         .Include(b => b.Notes) 
         .First(user => user.Id == entity.Id) 
         .Notes; 
      }