修改实体框架中的数据库6 [英] Alter Database in Entity Framework 6

查看:91
本文介绍了修改实体框架中的数据库6的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的代码中将EF更新为EF 6.0.2,我有以下代码:

  applicationDbContext。数据库.ExecuteSqlCommand(@ALTER DATABASE 
CURRENT SET RECOVERY FULL;);

更新后,我收到以下错误消息:


我有解决了一个TransctionalBehavior的问题,像下面的代码:

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

我的问题:




  • 为什么我会收到这个错误与EF 6?

  • 我的修复是一个有效的解决方案的问题或恶魔隐藏在这个解决方案后面?

  • 有什么其他方法可以解决问题吗?



任何帮助将不胜感激! b $ b

解决方案

EF 6使用ExecuteSqlCommand更改交易的使用


从Entity Framework 6.0开始,默认情况下,ExecuteSqlCommand()将在事务中将命令包装(如果尚未存在)。这种方法有重载,如果你愿意,你可以重写这个行为。


EF 5的行为方式不一样。您的修复是适当的。


现在可以指定一个TransactionalBehavior标志来指示EF如何使用此命令处理事务。




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

通过使用DoNotEnsureTransaction标志,EF在执行命令之前不会启动事务。这允许ALTER DATABASE命令成功执行。



http://www.danbartram.com/entity-framework-6-and-executesqlcommand/


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!?

解决方案

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.

http://www.danbartram.com/entity-framework-6-and-executesqlcommand/

这篇关于修改实体框架中的数据库6的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆