asp.net-mvc – 更新实体框架MVC中的子实体
我在我的视图中显示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); 有更好的方法来更新所有子实体吗? 解决方法
将更新应用于断开连接的实体时的标准模式如下:
>将根实体附加到上下文以在图表中启用更改跟踪 采用这种方法意味着您可以将依赖性要求降低到根实体的单个存储库. 例如,假设您只处理更新: 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代码直接输入浏览器,因此可能/将会有一些拼写错误. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
- asp.net – RegisterStartupScript和执行顺序
- [你必须知道的.NET] 第四回:后来居上:class和struct
- asp.net – 如何从TableAdapter中检索存储过程返回值
- asp.net core 自定义异常处理中间件
- asp.net-mvc和webforms共存
- 实体框架 – ASP.NET Web Api 2/EF6首次调用初始化性能
- .net – 包恢复失败.回滚包更改 – Serilog.AspNetCore
- asp.net-mvc-3 – 任何好的样品开始使用Dapper?
- asp.net – modalpopupextender取消按钮,就好像它正在回发一
- 在WebApi Core ConfigureServices中访问services.AddScoped