I am using EF6 with code first approach. I have a case where I am trying to apply same transaction over 2 different databases. Find my code below for the reference,
using (var scope = new TransactionScope(TransactionScopeOption.RequiresNew, TimeSpan.FromSeconds(6000)))
{
using (var dbContext = new MyDbContext())
{
try
{
/*
* some operations on dbContext
*
*/
using (IDbConnection conn = new SqlConnection(NewConnectionString))
{
string query = " ALTER TABLE [dbo].[TableName]...........";
conn.Execute(query); // I am using a dapper to call this execute query
}
}
catch (Exception ex)
{
throw;
}
}
scope.Complete();
}
The first section in try block does some normal operations on tables by using linq.
The second section where I have used IDbConnection, I am executing some query using dapper on another database. I can execute everything fine without error, but I'm getting error after I complete the scope. It throws error as The transaction has aborted. Everything works fine whenever I skip dapper execution section. I have checked many solutions and also tried to put separate transaction for dapper section but nothing worked. My requirement is to put all the statements under single transaction. Is that possible? How?
Related
I have got two DbContexts(One Model-first and the other one is code first) which connects to two different databases in MSSQL.
Now when you call SaveChanges from any class, it writes data to both the databases at the same time using TransactionScope class. Code looks like below.
using (TransactionScope scope = new TransactionScope())
{
using (Schema1Entities db1 = new Schema1Entities())
{
db1.SaveChanges();
}
using (Schema2Entities db2 = new Schema2Entities())
{
db2.SaveChanges();
}
scope.Complete();
}
The problem raises during runtime. it is saying that
An exception of type 'System.Data.Entity.Core.EntityException'
occurred in EntityFramework.SqlServer.dll but was not handled in user
code
Additional information: The underlying provider failed on Open.
Inner-exception message - {"The partner transaction manager has
disabled its support for remote/network transactions. (Exception from
HRESULT: 0x8004D025)"}
Turned on MSDTC, and no firewall is blocking the MSDTC.
Need help immediately.
As per the comments under the question, this solved the issue:
using (TransactionScope scope = new TransactionScope())
{
using (Schema1Entities db1 = new Schema1Entities())
using (Schema2Entities db2 = new Schema2Entities())
{
db1.SaveChanges();
db2.SaveChanges();
}
scope.Complete();
}
I have an connection to LocalDB database:
Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-mysite-20160510105433.mdf
I used code first with Entity Framework and the following piece of code:
var tran = this.context.Database.BeginTransaction();
//some operations on dbcontext
tran.Rollback();
where context variable is simple DbContext instance.
THe exception "The underlying provider failed on rollback" is thrown.
Such an exception is not thrown when using normal, SQL Server connection.
Does it mean that localdb doesn't support transaction? If yes, how to achieve it?
Or does it come from that connections run per process, so when query is over then connection is closed automatically?
Edit: sample operations that I perform:
var myEntity = new MyEntityA();
this.context.MyEntitiesA.Add(myEnttiy).
this.context.Save(); //save to retreive id
// some playing with id
var mySecondEntity= new MyEntityB(){ MyEntityAId = myEntityA.Id, //other data gethered in "playing part" } ;
this.context.MyEntitiiesB.Add(mySecondEntity).
this.context.Save(); //need to rollback first, when here fails.
So I want to enclose within transaction:
using (var tran = this.context.Database.BeginTransaction())
{
try
{
// operations
tran.Commit();
}
catch (Exception ex)
{
// stuff
tran.Rollback();
}
}
So as you can see transaction is useful here.
I need to create a simple dotnet application which is going to call a stored procedure inside a loop (the stored procedure accepts few parameters and add them to a table). The requirement is that either all the rows get inserted or non.
To ensure this I've used:
using (TransactionScope scope = new TransactionScope())
{
foreach (EditedRule editedRules in request.EditedRules)
{
...stored procedure call
}
}
I've never used TransactionScope before, can someone please let me know if this code will work and will all my rows be rolled back.
I would also appreciate if there is a better approach to this.
Assuming that your stored procedure does not create and commit its own transaction, this code will work, with one change: your code needs to code scope.Complete() before the end of the using block; otherwise, the transaction is going to roll back.
using (TransactionScope scope = new TransactionScope()) {
foreach (EditedRule editedRules in request.EditedRules) {
...stored procedure call
}
scope.Complete(); // <<== Add this line
}
The idea behind this construct is that the call of Complete will happen only if the block exits normally, i.e. there's no exception in processing the loop. If an exception is thrown, scope would detect it, and cause the transaction to roll back.
The only thing I would call out about your code is to make sure to do a scope.Complete() in order to commit the transaction:
using (TransactionScope scope = new TransactionScope())
{
foreach (EditedRule editedRules in request.EditedRules)
{
// stored proc
}
scope.Complete();
}
if any exceptions occur during the using block, the transaction would be rolled back.
I think this is what you're looking for:
using (var transaction = conn.BeginTransaction()) {
try
{
transaction.Commit();
}
catch
{
transaction.Rollback();
throw;
}
}
I'm using SQL Server 2008 R2 and trying to use transactions.
First a question about transactions in .net and SQL Server. If I have something like this
try {
var transactionOption = new TransactionOptions();
transactionOption.IsolationLevel = IsolationLevel.ReadCommitted;
transactionOption.Timeout = TransactionManager.MaximumTimeout;
using (var scope = new TransactionScope(TransactionScopeOption.RequiresNew, transactionOption)) {
//create question this creates a new question in the database
Helpers.CreateQuestionBankItem(ref mappedOldNewQuestionItemGuid, missingQuestionBankItems);
//question created
//query database for the code of the newly inserted question, will the database give me the code since Complete has not been called as yet?
scope.Complete();
}
}
catch (Exception ex) {
throw;
}
//query database for the code of the newly inserted question, will the database give me the code since Complete has been called as now?
At which point should I call the database to ask for the code of the newly inserted question. Now my second question, before I ask I found this link Nested Transaction . In the light of the above link I want to still ask that if I have something like this
try {
var transactionOption = new TransactionOptions();
transactionOption.IsolationLevel = IsolationLevel.ReadCommitted;
transactionOption.Timeout = TransactionManager.MaximumTimeout;
using (var outerscope = new TransactionScope(TransactionScopeOption.RequiresNew, transactionOption)) {
try {
var transactionOption = new TransactionOptions();
transactionOption.IsolationLevel = IsolationLevel.ReadCommitted;
transactionOption.Timeout = TransactionManager.MaximumTimeout;
using (var innerscope = new TransactionScope(TransactionScopeOption.RequiresNew, transactionOption)) {
//create question this creates a new question in the database
Helpers.CreateQuestionBankItem(ref mappedOldNewQuestionItemGuid, missingQuestionBankItems);
//question created
//query database for the code of the newly inserted question, will the database give me the code since Complete has not been called as yet?
innerscope.Complete();
}
}
catch (Exception ex) {
}
//query database for the code of the newly inserted question, will the database give me the code since Complete has been called as now?
outerscope.Complete();
}
}
catch (Exception ex) {
throw;
}
If my innerscope completes, will querying SQL Server give me the code of the newly created question.
What happens if the inner scope throws an exception and I gobble it up, will the outer scope also be disposed off?
Does calling innerscope.Complete() completes that inner scope?
If you want to recover from a failure in a transactional context you need to use transaction savepoints. Unfortunately the managed System.Transaction has no support for savepoints. Not only that, but you won't be able to use savepoints, even directly, if you use transaction scopes, because the transaction scope will escalate to distributed transactions and savepoints do not work in distributed contexts.
You can use instead the platform specific SqlTransaction which supports Save() for savepoints. See Exception Handling and Nested Transactions for an example of transaction-aware exception handling.
I have a typed dataset for a table called People. When you call the update method of a table adapter and pass in the table, is it run as a transaction?
I'm concerned that at some point the constraints set in the xsd will pass but the database will reject this item for one reason or another. I want to make sure that the entire update is rejected and I'm not sure that it just accepts what it can until that error occurs.
If it runs as a transaction I have this
Auth_TestDataSetTableAdapters.PeopleTableAdapter tableAdapter = new Auth_TestDataSetTableAdapters.PeopleTableAdapter();
Auth_TestDataSet.PeopleDataTable table = tableAdapter.GetDataByID(1);
table.AddPeopleRow("Test Item", 5.015);
tableAdapter.Update(table);
But if I have to manually trap this in a transaction I wind up with this
Auth_TestDataSetTableAdapters.PeopleTableAdapter tableAdapter = new Auth_TestDataSetTableAdapters.PeopleTableAdapter();
Auth_TestDataSet.PeopleDataTable table = tableAdapter.GetDataByID(1);
tableAdapter.Connection.Open();
tableAdapter.Transaction = tableAdapter.Connection.BeginTransaction();
table.AddPeopleRow("Test Item", 5.015);
try
{
tableAdapter.Update(table);
tableAdapter.Transaction.Commit();
}
catch
{
tableAdapter.Transaction.Rollback();
}
finally
{
tableAdapter.Connection.Close();
}
Either way works but I am interested in the inner workings. Any other issues with the way I've decided to handle this type of row addition?
-- EDIT --
Determined that it does not work as a transaction and will commit however many records are successful until the error occurs. Thanks to the helpful post below a bit of that transactional code has been condensed to make controlling the transaction easier on the eyes:
Auth_TestDataSetTableAdapters.PeopleTableAdapter tableAdapter = new Auth_TestDataSetTableAdapters.PeopleTableAdapter();
Auth_TestDataSet.PeopleDataTable table = tableAdapter.GetDataByID(1);
try
{
using (TransactionScope ts = new TransactionScope())
{
table.AddPeopleRow("Test Item", (decimal)5.015);
table.AddPeopleRow("Test Item", (decimal)50.015);
tableAdapter.Update(table);
ts.Complete();
}
}
catch (SqlException ex)
{ /* ... */ }
Your approach should work.
You can simplify it a little though:
using (TransactionScope ts = new TransactionScope())
{
// your old code here
ts.Complete();
}