我正在EF6 code first一个WinForm项目中工作。我使用以下方法从中读取实体Db,更新它们,然后将它们保存回Db:
Linq to entities使用(阅读DbContext处置后)阅读实体图- 向最终用户显示读取
Entity的图表。 - 最终用户可以将此更改应用于
Entity图形:- 更新根实体
- 添加一些子实体
- 编辑一些子实体
- 删除一些子实体
- 用户调用一个方法来将他的更改持久化到
Db - 创建一个新
DbContext实例。 - 重新加载相同
Entity的图表Db - 使用将所有属性的值从用户实体映射到重新加载的实体
AutoMapper - 将 6 步的结果实体附加到我的
DbContextusingGraphDiff 调用
DbContext.SaveChanges();以保持更改Db
var 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并且它们Id的 s 将被分配。但是在对象中Child13.Id,我可以手动更新s 但我正在寻找通用方法来使用生成的 s更新这些值。Child22.Identity0IdIdDbId