栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

在EF中更新父实体时如何添加/更新子实体

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在EF中更新父实体时如何添加/更新子实体

因为要发布到WebApi控制器的模型是与任何实体框架(EF)上下文分离的,所以唯一的选择是从数据库中加载对象图(包括其子项的父项),并比较已添加,删除或添加了哪些子项。更新。(除非您认为在分离状态下(在浏览器中或任何位置)使用自己的跟踪机制来跟踪更改,我认为这比以下情况更为复杂。)它看起来像这样:

public void Update(UpdateParentModel model){    var existingParent = _dbContext.Parents        .Where(p => p.Id == model.Id)        .Include(p => p.Children)        .SingleOrDefault();    if (existingParent != null)    {        // Update parent        _dbContext.Entry(existingParent).CurrentValues.SetValues(model);        // Delete children        foreach (var existingChild in existingParent.Children.ToList())        { if (!model.Children.Any(c => c.Id == existingChild.Id))     _dbContext.Children.Remove(existingChild);        }        // Update and Insert children        foreach (var childModel in model.Children)        { var existingChild = existingParent.Children     .Where(c => c.Id == childModel.Id)     .SingleOrDefault(); if (existingChild != null)     // Update child     _dbContext.Entry(existingChild).CurrentValues.SetValues(childModel); else {     // Insert child     var newChild = new Child     {         Data = childModel.Data,         //...     };     existingParent.Children.Add(newChild); }        }        _dbContext.SaveChanges();    }}

...CurrentValues.SetValues
可以接受任何对象,并根据属性名称将属性值映射到附加的实体。如果模型中的属性名称与实体中的名称不同,则不能使用此方法,必须逐个分配值。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/576236.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号