2017-08-01 66 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; 
      }