Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alter Database in Entity Framework 6

Tags:

I have update my EF to EF 6.0.2 in my code I have the following line of code:

 applicationDbContext.Database .ExecuteSqlCommand(@"ALTER DATABASE  CURRENT SET RECOVERY FULL;"); 

After updating I get the following error message:

ALTER DATABASE statement not allowed within multi-statement transaction.

I have fixed the problem with a TransctionalBehavior like the the code below:

applicationDbContext.Database.ExecuteSqlCommand( TransactionalBehavior.DoNotEnsureTransaction, @"ALTER DATABASE CURRENT SET RECOVERY FULL;"); 

My question:

  • Why I'm getting this error with EF 6?
  • My fix is a valid fix for the problem or a devil hiding behind this solution?
  • Is there any other approach to solve the problem?

Any help will be greatly appreciated!?

like image 507
Bassam Alugili Avatar asked Feb 11 '14 10:02

Bassam Alugili


People also ask

How do I update my Entity Framework database?

After creating a migration file using the add-migration command, you have to update the database. Execute the Update-Database command to create or modify a database schema. Use the –verbose option to view the SQL statements being applied to the target database.

How do I update my Entity Framework database first?

Right-click anywhere on the design surface, and select Update Model from Database. In the Update Wizard, select the Refresh tab and then select Tables > dbo > Student. Click Finish.


2 Answers

EF 6 changes the use of transactions with ExecuteSqlCommand

Starting with Entity Framework 6.0, ExecuteSqlCommand() by default will wrap the command in a transaction if one was not already present. There are overloads of this method that allow you to override this behavior if you wish.

EF 5 did not behave the same way. Your fix is appropriate.

You can now specify a TransactionalBehavior flag to instruct EF on how to handle transactions with this command.

var sqlCommand = String.Format("ALTER DATABASE {0} SET SINGLE_USER                                  WITH ROLLBACK IMMEDIATE"); db.Database.ExecuteSqlCommand(TransactionalBehavior.DoNotEnsureTransaction,                                sqlCommand); 

By using the DoNotEnsureTransaction flag, EF will not start a transaction before executing the command. This allows the ALTER DATABASE command to successfully execute.

like image 155
Eric J. Avatar answered Sep 30 '22 09:09

Eric J.


If you are using Code First approach possible solution is

public partial class AlterDatabase : DbMigration {     public override void Up()     {                                                    Sql("ALTER DATABASE CURRENT SET RECOVERY FULL", true);     }      public override void Down()     {      } } 
like image 45
Alex Pashkin Avatar answered Sep 30 '22 10:09

Alex Pashkin