[英]Entity Framework SaveChanges is saving unchanged record (via stored procedure mapping)
[英]Requiring an Id from SaveChanges, whilst saving? Entity Framework
我將一條記錄插入數據庫,如下所示:
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);
}
}
}
問題是,由於我沒有'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();
}
根據您的描述,我想您正在數據庫中使用自動生成的ID。 如果在上下文上執行SaveChanges
,您將不會收到此ID。 您必須將操作分為兩個單獨的修改:
public override int SaveChanges()
{
// call base context saving operation to insert all Transactions
base.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.TransactionUpdates.Add(update);
}
}
// save changes again to insert all TransactionUpdates
base.SaveChanges();
}
您應該將其包裝到TransactionScope
以執行整個保存為原子操作。
如果您尚未插入TransactionId,則無論如何在您的對象中都有它。 將您的對象作為參數傳遞給重載的方法SaveChanges並使用它傳遞Id
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.