私はプロジェクトEF6 code first
で働いています。WinForm
からエンティティを読み取りDb
、更新してから に保存するために、次の方法を使用しましたDb
。
- を使用してエンティティグラフを読み取る ( disposes
Linq to entities
を読み取った後)DbContext
- 読み取っ
Entity
たグラフをエンド ユーザーに表示します。 - エンド ユーザーは、この変更を
Entity
グラフ に適用できます。- ルート エンティティの更新
- いくつかの子エンティティを追加
- 一部の子エンティティを編集する
- いくつかの子エンティティを削除します
- ユーザーがメソッドを呼び出して変更を永続化する
Db
- 新しい
DbContext
インスタンスを作成します。 Entity
同じのグラフをリロードしますDb
- を使用して、すべてのプロパティの値をユーザー エンティティからリロードされたエンティティにマップします。
AutoMapper
- 6 ステップの結果エンティティを my
DbContext
usingに添付しますGraphDiff
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();
}
それはうまく動作します、
2 番目のグラフでは、ユーザーによって追加された Child13 と Child22 が呼び出され、uow.SaveChanges()
それらが保存されDb
、そのId
s が割り当てられます。しかしChild13.Id
、オブジェクトではChild22.Id
まだ、手動でs を更新できますが、生成された s でこれらの値を更新する一般的な方法を探しています。entity
0
Id
Id
Db
Id