7

私はASP.NETでコードの最初のマイグレーションを使用してWebアプリケーションを開発しています。これはローカルでは問題なく動作しますが、Azureにデプロイした後は、コードの最初の移行は実行されません。私はthis tutorialを何度かステップバイステップで行ってきましたが、セットアップに間違っている箇所を見つけられませんでした。EntityFramework Azureにデプロイした後にコードの最初のマイグレーションが実行されない

DBコンテキスト:

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> 

コードFi最初の移行の設定展開のWeb.config

における展開の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> 

接続文字列で

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

エンティティフレームワークのセクション

<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> 
+0

配備されたweb.configファイルを調べましたか? – ErikEJ

+0

いいえ、データベースとの接続は問題ありません。問題は、移行が適用されておらず、DBがシードされていないことです。 – nest

+0

@ErikEJこの情報を含む質問を修正しました。実際には、 ''または ' nest

答えて

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.Debug.configおよびWeb.Release.configを公開または構成する前に、Web.configの接続文字列を置き換えます。

+0

これは意味があります。情報ありがとう。 –

+0

はい、同じコードが「後の段階」で正常に完了したが、シード操作で失敗したため、何が問題なのか分かりません – nest

7

あなたはすでにApplicationDbContextコンストラクタでそれを提供するため、それは、「文脈」セクション内の接続文字列を提供必要はありませんソリューション

でWeb.configファイルを更新することができます。

また、この設定では、パブリケーションウィザードで[コードを最初に実行する]をオフにすることができます。

あなたの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> 

2

あなたが作成している場合がありますので、それが機能していない/デプロイで他の接続を選択ウィザード。展開された接続文字列で2つの接続文字列を見ることができます。

第二の接続文字列はまた、EFのsecitonにreferecenedさ - 最初れたconnectionStringを使用している状況において

と、 - パブリックApplicationDbContext():ベース( "DefaultConnectionを"、throwIfV1Schema:false)を{}

ここに名前を変更すると、問題が解決します。

+0

これは意味をなさない。しかし、どうすればこの「他の」接続を取り除くことができるのか分かりますか?私は実際にそれを作成しようとは考えていませんでした。開発と生産の両方に "DefaultConnection"を使用したいと思います。 – nest

+0

Deploy Wizardでこの接続文字列を使用しているオプションのチェックを外してください。これは役に立ちます。 –

+0

解決できましたか?私はフィードバックを聞くのが大好きです。 –

1

移行プロセスをさらに制御したい場合は、スタートアップで移行を処理できます。コンテキストを作成し、DBMigratorを(使用することによって認証)保留中の移行適用するクラス:これは、直接あなたの問題を解決しないことがあり、それはより多くの制御を可能にし、あなたがどうかを確認することができる必要がありますが

//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(); 

を移行は少しdebbugingと適用されません。

関連する問題