【发布时间】:2014-08-06 07:45:22
【问题描述】:
我在 WinForm 项目中与 EF6 code first 合作。
我使用以下方法从Db 读取实体,更新它们,然后将它们保存回Db:
- 使用
Linq to entities读取实体图(在读取DbContext处置后) - 向最终用户显示读取的
Entity图表。 - 最终用户可以将此更改应用于
Entity图表:- 更新根实体
- 添加一些子实体
- 编辑一些子实体
- 删除一些子实体
- 用户调用一个方法将他的更改持久化到
Db - 创建一个新的
DbContext实例。 - 从
Db重新加载相同的Entity的图表 - 使用
AutoMapper将所有属性的值从用户实体映射到重新加载的实体 - 使用
GraphDiff将6步的结果实体附加到我的DbContext -
致电
DbContext.SaveChanges();以将更改保留到Dbvar root = new MyDbcontext() .Roots .LoadAggregation() .ToList(); // LoadAggregation in this case, means following codes: // .Include("Child1") // .Include("Child2") root.Child1s.Remove(child11); root.Child1.Add(Child13); // root.Child2.Add(Child22); using(var uow = new UnitOfWork()) { uow.Repository<Root>().Update(root); uow.Repository<AnotherRoot>().Update(anotherRoot); //user may want to update multiple Roots uow.SaveChanges(); <---- at this point Child13.Id and Child22.Id generated by Db }
public void Update(Root entity) //Update method in my Repository class
{
var context = new MyDbcontext();
var savedEntity = context.Roots //reload entity graph from db
.LoadAggregation()
.ToList();
Mapper.Map(entity,savedEntity); // map user changes to original graph
context.UpdateGraph(savedEntity, savedEntity.MappingConfiguration); // attach updated entity to dbcontext using graphdiff
}
public void SaveChanges() // SaveChanges() in UnitofWork class
{
context.SaveChanges();
}
效果很好,
在第二张图中,用户添加了 Child13 和 Child22,当我调用 uow.SaveChanges() 时,他们将保存到 Db,并且他们的 Ids 将被分配。但是entity 中的Child13.Id 和Child22.Id 对象是0,但我可以手动更新Ids 但我正在寻找通用 方法来更新这些Id 值与Db 生成Ids。
【问题讨论】:
标签: c# entity-framework ef-code-first repository graphdiff