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创建并持久化到数据库的,当我稍后从数据库中获取实体时
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
通过调试器显示
用户1
之前
第一个上下文已被释放,是一个初始化的
List<Note>
用户2
在新上下文中创建的为null。
我的背景很简单:
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中生成的表可以发现外键确实存在:
笔记
用他们的
Creator
Id
为什么会这样?