Entity Framework Core - How to handle Related Entity Mapping and Saving

天大地大妈咪最大 提交于 2019-12-11 17:24:18

问题


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; }
}

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);
} 

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...


回答1:


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!



来源:https://stackoverflow.com/questions/50733417/entity-framework-core-how-to-handle-related-entity-mapping-and-saving

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!