简体   繁体   中英

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

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

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM