如何在EF Core中附加添加孩子的图表?
private static void AttachGraphWithExistingParentNewChild()
{
Class class;
using (var context = new SchoolContext())
{
class = context.Classes.FirstOrDefault(s => s.Name.Contains("AA"));
}
class.Students.Add(new Student{Name= "Youssef" });
using (var context = new SchoolContext())
{
context.ChangeTracker.TrackGraph(class, e=>e.Entry.State = EntityState.Added);
}
}
此方法将添加父级和子级,但这不是真的,我想只添加子级并让父级保持不变。
答案 0 :(得分:0)
你无法检查e.Entry.IsKeySet吗? e.Entry.State = e.Entry.IsKeySet? EntityState.Unchanged:EntityState.Added (假设父母将设置Id而不是孩子)