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;
}
通过调试器检查user1
和user2
揭示user1
,其所述第一上下文的处置之前创建,是已初始化的List<Note>
包含0个项目,而user2
(在新的上下文中创建)为空。
我的背景很简单:
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中的表显示,外键确实存在:
加入Note
新的实例与他们Creator
属性设置等于我的用户的Id
产生完全相同的结果。
这是怎么发生的?
代替'公开名单票据{得到;组; }'使用'公共虚拟ICollection 笔记{get;组; }' –
[实体框架加载相关实体](https://msdn.microsoft.com/en-us/data/jj574232.aspx) –