问题
An error occurred while starting a transaction on the provider connection. See the inner exception for details. "Nested transactions are not supported." Inner Exception
public bool Insert(myModel model)
{
entities.Database.Connection.Open();
using (DbTransaction trans = entities.Database.Connection.BeginTransaction())
{
try
{
table1 obj1 = new table1
{
AccountHolderName = model.AccountHolderName,
AccountNumber = model.AccountNumber,
Address = model.Address,
};
entities.table1.Add(obj1);
entities.SaveChanges();
long id = obj1.ID;
table2 obj = new table2
{
ID = model.ID == 1 ? id : model.ID,
Username = model.Email,
Password = model.Password,
};
entities.table2.Add(obj2);
entities.SaveChanges();
trans.Commit();
}
catch (Exception)
{
trans.Rollback();
}
finally
{
entities.Database.Connection.Close();
}
}
}
回答1:
It is probably caused by 2 different connections used in transaction. You should control connection manually:
objectContext = ((IObjectContextAdapter)entities).ObjectContext;
try{
objectContext.Connection.Open();
using (var tran = new TransactionScope()) {
table1 obj1 = new table1
{
AccountHolderName = model.AccountHolderName,
AccountNumber = model.AccountNumber,
Address = model.Address,
};
entities.table1.Add(obj1);
entities.SaveChanges();
table2 obj = new table2
{
ID = model.ID == 1 ? id : model.ID,
Username = model.Email,
Password = model.Password,
};
entities.table2.Add(obj2);
entities.SaveChanges();
tran.Complete();
}
}
finally{
objectContext.Connection.Close();
}
回答2:
you are adding two objects at a time in a same function so you get error table1 object data and table 2 object data add in different block.
来源:https://stackoverflow.com/questions/16849954/in-entity-framework-4-0-nested-transactions-are-not-supported-error-is-display