實體框架 - 在調用'SaveChanges'之前是否有任何方法在事務內部檢索新創建的ID(標識)?實體框架 - 在交易中的'SaveChanges'之前檢索ID
我需要一個第二個插入的ID,但它始終返回0 ...是由數據庫生成
ObjectContext objectContext = ((IObjectContextAdapter)context).ObjectContext;
objectContext.Connection.Open();
using (var transaction = objectContext.Connection.BeginTransaction())
{
foreach (tblTest entity in saveItems)
{
this.context.Entry(entity).State = System.Data.EntityState.Added;
this.context.Set<tblTest>().Add(entity);
int testId = entity.TestID;
.... Add another item using testId
}
try
{
context.SaveChanges();
transaction.Commit();
}
catch (Exception ex)
{
transaction.Rollback();
objectContext.Connection.Close();
throw ex;
}
}
objectContext.Connection.Close();
http://stackoverflow.com/questions/6029711/id-of-newly-added-entity-before-savechanges – Zaki
哦,希望有一種方式,但謝謝。 – user1948635