简体   繁体   English

在保存的同时要求SaveChanges提供一个ID? 实体框架

[英]Requiring an Id from SaveChanges, whilst saving? Entity Framework

I am inserting a record into the database, which looks like this: 我将一条记录插入数据库,如下所示:

class Transaction
{
   int Id;
}

What I want, is when I insert this object, I want to create another record, like this: 我想要的是,当我插入该对象时,我想要创建另一个记录,如下所示:

class TransactionUpdate
{
   int StartingTransactionId;
   int EndingTransactionId;
}

What I have so far, is a loop in my SaveChanges on the DbContext, which takes new Transaction objects that will be created and creates TransationUpdate objects and attaches these to the DbContext. 到目前为止,我在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);
     }
   }
 }

The problem is, I cannot properly create a TransactionUpdate because I do not have 'EndingTransactionId', or, the Id of the Transaction I am currently inserting. 问题是,由于我没有'EndingTransactionId',或者我当前正在插入的交易ID,我无法正确创建TransactionUpdate。

How can I solve this problem? 我怎么解决这个问题?

Many Thanks. 非常感谢。

SOLVED 解决了

I have done what Ladislav suggested and am now creating a list of items to add, along with references to the objects that are required to insert them. 我已经完成了Ladislav的建议,现在正在创建要添加的项目的列表,以及对插入它们所需的对象的引用。 Thus: 从而:

    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();
        }

Based on your description I guess you are using autogenerated Id in database. 根据您的描述,我想您正在数据库中使用自动生成的ID。 You will not receive this Id befere executing SaveChanges on the context. 如果在上下文上执行SaveChanges ,您将不会收到此ID。 You have to divide operation into two separate modifications: 您必须将操作分为两个单独的修改:

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();  
} 

You should wrap it into TransactionScope to perform whole saving as atomic operation. 您应该将其包装到TransactionScope以执行整个保存为原子操作。

If you haven't inserted TransactionId, you have it anyway in your object. 如果您尚未插入TransactionId,则无论如何在您的对象中都有它。 Pass your object as parameter to an overloaded method SaveChanges and use it to pass the Id 将您的对象作为参数传递给重载的方法SaveChanges并使用它传递Id

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM