Alter Database in Entity Framework 6

前端 未结 2 2139
南笙
南笙 2020-12-18 18:30

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 SE         


        
相关标签:
2条回答
  • 2020-12-18 19:09

    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.

    0 讨论(0)
  • 2020-12-18 19:25

    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()
        {
    
        }
    }
    
    0 讨论(0)
提交回复
热议问题