我正在向数据库中插入一条记录,如下所示:
class Transaction
{
int Id;
}
我想要的是,当我插入这个对象时,我想创建另一条记录,如下所示:
class TransactionUpdate
{
int StartingTransactionId;
int EndingTransactionId;
}
到目前为止,我在 DbContext 上的 SaveChanges 中有一个循环,它采用将要创建的新 Transaction 对象并创建 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);
}
}
}
问题是,我无法正确创建 TransactionUpdate,因为我没有“EndingTransactionId”,或者我当前插入的交易的 Id。
我怎么解决这个问题?
非常感谢。
解决了
我已经完成了 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();
}