首先更新父实体并在EF核心代码中添加新的儿童实体

发布于 2025-02-10 23:35:06 字数 591 浏览 3 评论 0原文

public class Parent 
{
   public int ID {get;set;}
   public string Name {get;set;}
   public List<Child> Children {get;set;}      
}

public class Child
{
  public int ID {get;set;}
  public string AnotherProp {get;set;}
  public int ParentId {get;set;}
}

的父母实体现在有一排,并且有2行。

从API中,我获得了该特定父行的更新以及插入新的子行(注意:插入新的孩子将有3个孩子)。我正在下面做以将新孩子添加到父母。

 existingParent.Children.Add(newChild);
 context.Parents.SaveChangesAsync();

但是我有例外: 异常:dbupdateconcurrencyException,异常:数据库操作预期会影响1行,但实际上影响了0行。由于已加载实体,因此可能已修改或删除数据。请建议。

I have below classes

public class Parent 
{
   public int ID {get;set;}
   public string Name {get;set;}
   public List<Child> Children {get;set;}      
}

public class Child
{
  public int ID {get;set;}
  public string AnotherProp {get;set;}
  public int ParentId {get;set;}
}

Now my Parent entity has one row and it has 2 child rows.

From api, I got an update for that particular parent row as well as insert new child row (note: after inserting new one there will be 3 children). I am doing below to add new child to the parent.

 existingParent.Children.Add(newChild);
 context.Parents.SaveChangesAsync();

But I am getting the exception :
Exception: DbUpdateConcurrencyException, ExceptionMessage: Database operation expected to affect 1 row(s) but actually affected 0 row(s). Data may have been modified or deleted since entities were loaded. Please advice.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文