加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – 更新实体框架MVC中的子实体

发布时间:2020-12-16 06:33:36 所属栏目:asp.Net 来源:网络整理
导读:我在我的视图中显示Parent实体及其子项,并使用户能够编辑父实体和子实体. 当用户点击“保存”时.只有在忽略子实体时才会修改父实体.我的工作就是这个. var addressRepo=_dataRepositoryFactory.GetDataRepositoryIPatientAddressRepository();foreach (var a
我在我的视图中显示Parent实体及其子项,并使用户能够编辑父实体和子实体.

当用户点击“保存”时.只有在忽略子实体时才会修改父实体.我的工作就是这个.

var addressRepo=_dataRepositoryFactory.GetDataRepository<IPatientAddressRepository>();
foreach (var address in entity.Addresses)
{
    addressRepo.Update(address);
}

_dataRepositoryFactory.GetDataRepository<IPatientContactRepository>().Update(entity.Contact);


var guardianRepo = _dataRepositoryFactory.GetDataRepository<IPatientGuardianRepository>();
foreach (var guardian in entity.Guardians)
{
    guardianRepo.Update(guardian);
}

_dataRepositoryFactory.GetDataRepository<IPatientDemographicRepository>().Update(entity.Demographic);

return _patientRepository.Update(entity);

有更好的方法来更新所有子实体吗?

解决方法

将更新应用于断开连接的实体时的标准模式如下:

>将根实体附加到上下文以在图表中启用更改跟踪
>这将整个对象图标记为EntityState.Unchanged,因此您需要遍历图形并按顺序设置状态
>将父实体标记为EntityState.Modified,以便保持其更改
>对于每个子实体,计算更改的性质(插入,删除或更新)并相应地标记其状态
>保存上下文后,图表中的更改将保持不变.

采用这种方法意味着您可以将依赖性要求降低到根实体的单个存储库.

例如,假设您只处理更新:

using (var context = new MyContext())
{
    context.attach(parentEntity);
    context.Entry(parentEntity).State = EntityState.Modified;

    context.Entity(parentEntity.ChildEntity1).State = EntityState.Modified;
    context.Entity(parentEntity.ChildEntity2).State = EntityState.Modidied;

    context.SaveChanges();
}

这通常被封装在您的存储库中的AttachAsModified方法中,该方法知道如何根据图的根实体“绘制对象图的状态”.

例如.

public class MyRepository<TEntity>
{
    public void AttachAsModified(TEntity entity)
    {
        _context.attach(entity);
        _context.Entry(entity).State = EntityState.Modifed;
        _context.Entity(entity.ChildEntity1).State = EntityState.Modified;
        // etc
        _context.SaveChanges();
    }   
}

如果您需要考虑插入或删除子实体,则会有额外的复杂性.这些归结为加载根实体及其子实体的当前状态,然后将子集与更新的根实体上的集进行比较.然后根据集合的重叠将状态设置为EntityState.Deleted或EntityState.Added.

NB代码直接输入浏览器,因此可能/将会有一些拼写错误.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读