Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stored Procedure without transaction in Entity Framework

I'm calling a stored procedure in Entity Framework 6 that can create Databases and tables if necessary. It is throwing the error;

Message "CREATE DATABASE statement not allowed within multi-statement transaction.\r\nALTER DATABASE statement not allowed within multi-statement transaction.\r\nDatabase 'CoreSnapshotJS3' does not exist. Make sure that the name is entered correctly." string

I do not want it in a transaction, and have used this to supress the transaction

using (var transation = new TransactionScope(TransactionScopeOption.Suppress))
{
    return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction("spCreateSnapshotFromQueue", snapshotQueueIDParameter);    
}

It still throws an error.

How do I stop automatic transactions?

like image 555
Founder Avatar asked Aug 25 '14 07:08

Founder


People also ask

Do stored procedures need transaction?

In stored procedures and triggers, the number of begin transaction statements must match the number of commit transaction statements. This also applies to stored procedures that use chained mode. The first statement that implicitly begins a transaction must also have a matching commit transaction.

Can we use Entity Framework with stored procedure?

You can use stored procedures either to get the data or to add/update/delete the records for one or multiple database tables. EF API creates a function instead of an entity in EDM for each stored procedure and User-Defined Function (UDF) in the target database.

Why you shouldn't use Entity Framework with transactions?

No process will be able to access the tables you have touched (even reading from it) during your transaction. That can lead to Deadlocks pretty fast and you want to avoid them at all costs! Rule of Thumb: Save only once per task and don't use transactions.

Is stored procedure transactional?

Stored procedures support all transactional commands, namely BEGIN/START TRANSACTION, COMMIT, and ROLLBACK.


1 Answers

I found a way:

var snapshotQueueIDParameter = new SqlParameter("SnapshotQueueID", entityId);
return _db.Database.ExecuteSqlCommand(TransactionalBehavior.DoNotEnsureTransaction,
        "EXEC spCreateSnapshotFromQueue @SnapshotQueueID", snapshotQueueIDParameter);
like image 89
Founder Avatar answered Sep 22 '22 09:09

Founder