实体框架核心-如何处理相关实体的映射和保存

实体框架核心-如何处理相关实体的映射和保存

问题描述:

我有两个相关的实体,它们之间是一对多的关系,如下所示:

I have two related entity which is one-to-many relationship like below:

class parent{
 public string parentName{get;set;}
 public virtual ICollection<child> childs { get; set; }
}

class child{
  public string childName{get;set;}
  public parent parent{get;set;}
  ["ForeignKey"]
  public int parentId {get; set;}
}
/// View Model
class VMParent{
  public string parentName{get;set;}
  /// a string array contains child name
  public string[] childlist { get; set; }
}

假设我的父母当前有2个孩子,名字为:( apple ,梨),现在我想通过网络api将其更新为包含3个子梨(苹果,橙子,香蕉),请注意,此处已删除现有子梨子 >并添加了2个新子项(橙色,香蕉),这里假设表子项中已经存在橙色,但香蕉不存在,应将其视为子表的新条目,我可以得到我从网络api主体视图模型中以字符串数组( [ apple, orange, banana] )的形式添加了孩子的名字的模型,例如:

Suppose my parent currently contains 2 child with name: (apple, pear), now I want to update it through web api to contain 3 child (apple, orange, banana), note here the existed child pear is removed and 2 new child(orange, banana) is added, here assume that orange is already existed in table child but banana is not, it should be considered as new entry to child table, and I can get my updated model with childs name in a string array(["apple", "orange", "banana"]) from web api body View Model like:

[HttpPut("{id}")]
public async Task<IActionResult> Update(string name, [FromBody]VMParent VMUpdateParent)
{
    if (ModelState.IsValid)
    {
        var existingParent = await _context.Parents
                            .Include(t => t.childs)
                            .SingleOrDefaultAsync(p => p.parentName == name);

        existingParent.parentName = updateParent.parentName;

        var childsToBeUpdated = updateParent.childList; /// ["apple","orange","banana"]

        /// HOW TO HANDLE or REBUILD the relationship that can
        /// 1) remove child (pear) from existingParent
        /// 2) add child "banana" to Child table
        /// 3) add childs (orange and banana) to existingParent?
        ......

        _context.Parents.Update(existingParent);
        await _context.SaveChangesAsync();

        return new NoContentResult();
    }
    return BadRequest(ModelState);
} 

是否存在诸如Entity Framework Core中SQL中的 MERGE语句?我真的很期待使用Entity Framework在真实世界中的应用程序中的更多教程...

Is there any "MERGE" statement like in SQL in Entity Framework Core? I am really looking forward to some more tutorials in real-world application with Entity Framework...

我已经找到了一个通过在视图模型 VMUpdateParent 与现有模型 existingParent 之间使用 AutoMapper 解决方案,删除不必要的子节点并添加新的子节点。

I have figured out one solution myself by using AutoMapper in between view model VMUpdateParent with existed model existingParent to remove unnecessary child node and add new child node.

但是,如果有人有任何改进或更好的解决方案,请随时在此处分享。预先谢谢!

However, if anyone has any improved or better solution, please feel free to share here. Thanks in advance!