[英]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: 假设我的父母当前有2个孩子,名字为( apple,pear ),现在我想通过Web api更新它以包含3个孩子( apple,orange,banana ),请注意,这里删除了已存在的子梨,并有2个新的孩子(添加了orange,banana),这里假定table child中已经存在orange了,但是香蕉不存在,应该将其视为child table的新条目 ,并且我可以在字符串数组中获得带有childs名称的更新模型( [“ apple”,“ orange”,“ banana”] )来自Web api主体视图模型,例如:
[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? 是否有任何“ MERGE”语句,例如Entity Framework Core中的SQL? 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. 我自己通过在视图模型VMUpdateParent与现有模型existParent之间使用AutoMapper来找出一种解决方案,以删除不必要的子节点并添加新的子节点。
However, if anyone has any improved or better solution, please feel free to share here. 但是,如果有人有任何改进或更好的解决方案,请随时在这里分享。 Thanks in advance! 提前致谢!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.