简体   繁体   English

实体框架种子部署SQL脚本错误

[英]Entity Framework Seed Deployment SQL Script error

As part of my Entity Framework deployment I'm trying to deploy some scripts onto a newly created database, however I got the following error; 作为实体框架部署的一部分,我试图将一些脚本部署到新创建的数据库中,但是出现以下错误;

ALTER DATABASE statement not allowed within multi-statement transaction. 多语句事务中不允许使用ALTER DATABASE语句。

My Code; 我的代码;

internal sealed class Configuration : DbMigrationsConfiguration<DBContext>
{
    public Configuration()
    {
        AutomaticMigrationsEnabled = true;
    }

    protected override void Seed(DBContext context)
    {
        context.Database.ExecuteSqlCommand(
            @"ALTER DATABASE MyDB SET ENABLE_BROKER
            CREATE QUEUE NewCarShareQueue;
            CREATE SERVICE NewCarShareService ON QUEUE NewNewCarShareQueue 
               ([http://schemas.microsoft.com/SQL/Notifications/PostQueryNotification]);");
    }
}

I've tried the following as well, making sure only one transaction is going through at once, and not shown here but disposing the current context and recreating it; 我也尝试了以下方法,以确保一次仅处理一次事务,此处未显示,但处理了当前上下文并重新创建了它。

internal sealed class Configuration : DbMigrationsConfiguration<DBContext>
{
    public Configuration()
    {
        AutomaticMigrationsEnabled = true;
    }

    protected override void Seed(DBContext context)
    {
        context.SaveChanges();
        context.Database.ExecuteSqlCommand(
           @"ALTER DATABASE MyDB SET ENABLE_BROKER");
    }
}

The Seed command is run after every successful migration run . 每次成功迁移运行后, 都会运行Seed命令。 It actually runs even if no migrations were pending. 即使没有迁移挂起,它实际上也会运行。 So it is a bad place to do any altering of the DB structure. 因此,更改数据库结构是一个不好的地方。

It is better to create a migration and do the ALTERs in there. 最好创建一个迁移并在那里执行ALTER。 When your model and migrations are in sync, run add-migration EnableQueue in the PM console. 当模型和迁移同步时,在PM控制台中运行add-migration EnableQueue That will give you an empty migration that you can now add your own statements to. 这将为您提供一个空迁移,您现在可以将自己的语句添加到其中。

Anyways, running SQL statements in a separate transaction in the Seed method is an interesting problem. 无论如何,在Seed方法中的单独事务中运行SQL语句是一个有趣的问题。 Something like this should work (haven't compiled it myself, so there's probably a few typos in it): 像这样的东西应该可以工作(我自己没有编译过,所以里面可能有一些错别字):

protected override void Seed(DBContext context)
{
  using(var tx = new TransactionScope(TransactionScopeOption.RequiresNew))
  using(var conn = new SqlConnection(context.Database.Connection.ConnectionString))
  {
    conn.Open()
    var command = conn.CreateCommand();
    command.CommandText = "ALTER DATABASE WHATEVER YOU WANT TO DO";
    command.ExecuteNonQuery();

    tx.Complete();
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM