EntityFramework代码在部署到Azure后未运行的第一次迁移

时间:2016-02-05 14:29:09

标签: asp.net-mvc entity-framework azure ef-code-first ef-migrations

我正在使用代码优先迁移在ASP.NET中开发Web应用程序。它在本地工作正常,但在部署到Azure后,代码首次迁移不会执行。我一直在跟踪this tutorial几次,但我无法发现我的设置有什么问题。以下是相关代码:

数据库上下文:

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext() : base("DefaultConnection", throwIfV1Schema: false) {}

    public DbSet<BC_Instance> BiocloudInstances { get; set; }

    static ApplicationDbContext() {}

    public static ApplicationDbContext Create()
    {
        return new ApplicationDbContext();
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        var conv = new AttributeToTableAnnotationConvention<SoftDeleteAttribute, string>(
           "SoftDeleteColumnName",
           (type, attributes) => attributes.Single().ColumnName);

        modelBuilder.Conventions.Add(conv);
    }
}

连接字符串:

(在发布时替换,但以防万一)

<add name="DefaultConnection" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=bcplatform2;Integrated Security=True;MultipleActiveResultSets=True" providerName="System.Data.SqlClient" /></connectionStrings>

代码优先迁移配置

internal sealed class Configuration : DbMigrationsConfiguration<bcplatform2.Models.ApplicationDbContext>
{
    public Configuration()
    {
        AutomaticMigrationsEnabled = false;
    }

    protected override void Seed(bcplatform2.Models.ApplicationDbContext context)
    {
        var userManager = new ApplicationUserManager(new UserStore<ApplicationUser>(context));
        var roleManager = new ApplicationRoleManager(new RoleStore<ApplicationRole>(context));
        const string name = {name here};
        const string password = {pass here};
        const string adminRole = {role};
        string[] roles = new string[] { adminRole, ApplicationRole.DefaultRoleName };

        foreach (string role in roles)
        {
            if (!context.Roles.Any(r => r.Name == role))
            {
                roleManager.CreateAsync(new ApplicationRole(role));
            }
        }

        if (!context.Users.Any(u => u.UserName == name))
        {
            var user = new ApplicationUser { UserName = name, Email = name, credit = 10 };

            userManager.Create(user, password);
            userManager.AddToRole(user.Id, adminRole);
            userManager.SetLockoutEnabled(user.Id, false);
        }
    }
}

发布向导 enter image description here

部署的Web.config中的实体框架部分

<entityFramework>
  <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
    <parameters>
      <parameter value="mssqllocaldb" />
    </parameters>
  </defaultConnectionFactory>
  <providers>
    <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
  </providers>
  <contexts>
    <context type="bcplatform2.Models.ApplicationDbContext, bcplatform2">
      <databaseInitializer type="System.Data.Entity.MigrateDatabaseToLatestVersion`2[[bcplatform2.Models.ApplicationDbContext, bcplatform2], [bcplatform2.Migrations.Configuration, bcplatform2]], EntityFramework, PublicKeyToken={token}">
        <parameters>
          <parameter value="DefaultConnection_DatabasePublish" />
        </parameters>
      </databaseInitializer>
    </context>
  </contexts>
</entityFramework>

部署的Web.config中的连接字符串

<connectionStrings>
  <add name="DefaultConnection" connectionString="Data Source=tcp:{serverid}.database.windows.net,1433;Initial Catalog={dbid};User Id={user};Password={password}" providerName="System.Data.SqlClient" />
  <add name="DefaultConnection_DatabasePublish" connectionString="Data Source=tcp:{serverid}.database.windows.net,1433;Initial Catalog={dbid};User ID={user};Password={password}" providerName="System.Data.SqlClient" />
</connectionStrings>

4 个答案:

答案 0 :(得分:7)

您可以在解决方案

中更新Web.config文件

没有必要在“context”部分中提供连接字符串,因为您已经在ApplicationDbContext构造函数中提供了它。

此外,使用此配置,您可以取消选中“发布向导”中的“执行代码首次迁移”。

您的EF部分应与此类似(最重要的是“上下文”部分):

<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
  <parameters>
    <parameter value="mssqllocaldb" />
  </parameters>
</defaultConnectionFactory>
<providers>
  <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
<contexts>
  <context type="TestWebApp.Models.AppContext, TestWebApp">
    <databaseInitializer type="System.Data.Entity.MigrateDatabaseToLatestVersion`2[[TestWebApp.Models.AppContext, TestWebApp], [TestWebApp.Migrations.Configuration, TestWebApp]], EntityFramework" />
  </context>
</contexts>

答案 1 :(得分:2)

它无效,因为您可能在部署向导中创建/选择了其他连接。在已部署的连接字符串中确认相同,您可以在其中看到两个连接字符串。

第二个连接字符串也在EF seciton中被引用 -

并且,在上下文中,您使用了第一个连接字符串 - public ApplicationDbContext():base(“DefaultConnection”,throwIfV1Schema:false){}

此处更改名称将解决您的问题。

答案 2 :(得分:1)

如果您希望对迁移过程有更多控制权,可以通过创建上下文并使用 DBMigrator()类来处理 Startup.Auth 中的迁移应用任何待处理的迁移:

//Get the connection string
var connectionString = ConfigurationManager.ConnectionStrings["DefaultConnection"];

//Instanciate the sql connection string builder
var builder = new System.Data.SqlClient.SqlConnectionStringBuilder(connectionString.ConnectionString);

//Create your context
var dbContext = new ApplicationDbContext(builder.ConnectionString);

//Check for null (Handle issue here).
if (dbContext == null) return;

//Get your configuration and specify the target database
var config = new Migrations.Configuration();
config.TargetDatabase = new DbConnectionInfo(builder.ConnectionString, "System.Data.SqlClient");

//Create the migrator using your config
var mig = new DbMigrator(config);

//Check for any pending migration to speed up the process and Update
//The migration will be applied here each time the application is published on azure   
if(mig.GetPendingMigrations().Any())mig.Update();

虽然这可能无法直接解决您的问题,但它允许更多控制,您应该能够看到迁移是否通过少量重新应用来应用。

答案 3 :(得分:1)

问题在于种子方法:

protected override void Seed(bcplatform2.Models.ApplicationDbContext context)
{
    var userManager = new ApplicationUserManager(new UserStore<ApplicationUser>(context));
    var roleManager = new ApplicationRoleManager(new RoleStore<ApplicationRole>(context));
    const string name = {name here};
    const string password = {pass here};
    const string adminRole = {role};
    string[] roles = new string[] { adminRole, ApplicationRole.DefaultRoleName };

    foreach (string role in roles)
    {
        if (!context.Roles.Any(r => r.Name == role))
        {
            roleManager.CreateAsync(new ApplicationRole(role));
        }
    }

    if (!context.Users.Any(u => u.UserName == name))
    {
        var user = new ApplicationUser { UserName = name, Email = name, credit = 10 };

        userManager.Create(user, password);
        userManager.AddToRole(user.Id, adminRole);
        userManager.SetLockoutEnabled(user.Id, false);
    }
}

它没有完成,但没有在出版物输出上显示任何错误,使得错误难以发现。我删除了种子方法,迁移工作正常。

将来避免类似问题的一些建议是不使用发布向导中的“在运行时使用此连接字符串”和“执行代码优先迁移”选项。如果出现问题,输出将不会总是显示错误,并且几乎无法控制Web.config的修改方式。

相反,在发布之前替换Web.config中的连接字符串,或者相应地配置Web.Debug.config和Web.Release.config。