public class Practice
{
public List<Participation> Participation { get; set; }
}
public class Participation
{
public string Id { get; set; }
public virtual Practice Practice { get; set; }
}
public void test()
{
var practice = _ctx.Practice.SingleOrDefault(p => p.Id == practiceId);
practice.Participations.AddRange(NewParticipations);
_ctx.Participation.AddRange(NewParticipations)
await _ctx.SaveChangesAsync();
}
如果我具备以上条件,我是否需要在test函数中使用第三行来保存新的参与者,或者Practice.Participations.AddRange()会隐式地处理此问题?
practice.Participations.AddRange
应该足够了。
如果从上下文已经跟踪的实体的导航属性中引用新实体,则将发现该实体并将其插入数据库。
来源:https : //docs.microsoft.com/zh-cn/ef/core/saving/related-data#adding-a-related-entity
您可以像这样观察它...
var practice = _ctx.Practice.SingleOrDefault(p => p.Id == practiceId);
practice.Participations.AddRange(NewParticipations);
Debug.WriteLine(_ctx.Participation.Count()); //note count
await _ctx.SaveChangesAsync();
Debug.WriteLine(_ctx.Participation.Count()); //count increased
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句