次のようなレコードをデータベースに挿入しています。
class Transaction
{
int Id;
}
私が欲しいのは、このオブジェクトを挿入するときに、次のように別のレコードを作成したいということです:
class TransactionUpdate
{
int StartingTransactionId;
int EndingTransactionId;
}
私がこれまでに持っているのは、DbContext の SaveChanges のループです。これは、作成される新しいトランザクション オブジェクトを取得し、TransationUpdate オブジェクトを作成して、これらを DbContext にアタッチします。
public override int SaveChanges()
{
foreach(var entry in this.ChangeTracker.Entries())
{
if(entry.Entity is Transaction)
{
var update = new TransactionUpdate();
update.StartingTransactionId = ((Transaction)entry.Entity).PreviousTransactionId;
update.EndingTransactionId = ((Transaction)entry.Entity).Id; // This is zero because the entity has not been inserted.
this.TransactionUpdates.Add(update);
}
}
}
問題は、「EndingTransactionId」または現在挿入しているトランザクションの ID がないため、TransactionUpdate を適切に作成できないことです。
どうすればこの問題を解決できますか?
どうもありがとう。
解決した
私は Ladislav が提案したことを実行し、追加するアイテムのリストと、それらを挿入するために必要なオブジェクトへの参照を作成しています。したがって:
public override int SaveChanges()
{
var transactionUpdatesToAdd = new List<Tuple<TransactionUpdate, Transaction>>();
foreach (var entry in this.ChangeTracker.Entries<Transaction>())
{
if (entry.State == EntityState.Added)
{
var update = new TransactionUpdate();
update.StartingTransactionId = ((Transaction)entry.Entity).PreviousTransactionId;
transactionUpdatesToAdd.Add(new Tuple<TransactionUpdate, Transaction>(update, entry.Entity));
}
}
using(var scope = new TransactionScope())
{
// Save new Transactions
base.SaveChanges();
// Update TransactionUpdates with new IDs
foreach (var updateData in transactionUpdatesToAdd)
{
updateData.Item1.EndingTransactionId = updateData.Item2.Id;
this.TransactionUpdates.Add(updateData.Item1);
}
// Insert the new TransactionUpdate entities.
return base.SaveChanges();
}