2017-04-13 14 views
0

私は、以下のいずれかのようDbContextから派生したコンテキストを持っている:パス接続文字列最初

public class StudentContext : DbContext 
{ 
public StudentContext(string connectionString) : base(connectionString) 
{ 
} 
protected override void OnModelCreating(DBModelBuilder modelBuilder) 
{ 
    base.OnModelCreating(modelBuilder); 
    System.Data.Entity.Database.SetInitializer(new MigrateDatabaseToLatestVersion<StudentContext, StudentMigrations.Configuration>()); 
} 

public DbSet<Students> Students {get; set;} 
} 

私がして、接続文字列を渡すためにしようとしている:

studentContext = new StudentContext(settings.ConnectionString) 

設定は、コンフィギュレーションファイルを読むことによって実行時にロードされます。 私はthisを試してみましたが、StudentContextコンストラクタ内で接続文字列をthis.Database.Connection.ConnectionStringを使用して設定しようとしました。どちらの場合でも、デフォルトのコンストラクタを提供するか、 IDbContextFactoryの私は私が仕事をする最初のオプションを取得することができれば、コード内で、したがって、静の使用を削減しようとしています

public class StudentContext : DbContext 
{ 
    public static string ConnectionString; 
public StudentContext(string connectionString) : base(ConnectionString = connectionString) 
{ 
} 

//And also provide a default implementation of the DbContext constructor: 
public StudentContext() : base(ConnectionString) 
{ 
} 

protected override void OnModelCreating(DBModelBuilder modelBuilder) 
{ 
    base.OnModelCreating(modelBuilder); 
    System.Data.Entity.Database.SetInitializer(new MigrateDatabaseToLatestVersion<StudentContext, StudentMigrations.Configuration>()); 
} 

public DbSet<Students> Students {get; set;} 
} 

、それは素晴らしいことだ:働く唯一の事はこれです。

答えて

2

MigrateDatabaseToLatestVersion from this answerの読み取り専用文字列に接続文字列がキャッシュされていることがわかります。クラスを更新するだけでした:

public class StudentContext : DbContext 
{ 
    public StudentContext(string connectionString) : base(connectionString) 
    { 
    } 

    protected override void OnModelCreating(DBModelBuilder modelBuilder) 
    { 
     base.OnModelCreating(modelBuilder); 
     System.Data.Entity.Database.SetInitializer(new MigrateDatabaseToLatestVersion<StudentContext, StudentMigrations.Configuration>(true)); //Passing true here to reuse the client context triggering the migration 
    } 

    public DbSet<Student> Students {get; set;} 
} 
0

エンティティの接続文字列を指定する必要があります。 DbContext内

SqlConnectionStringBuilder sqlString = new SqlConnectionStringBuilder() 
     { 
    DataSource = "SOURAV-PC", // Server name 
    InitialCatalog = "efDB", //Database 
      UserID = "sourav",   //Username 
      Password = "mypassword", //Password 
     }; 
     //Build an Entity Framework connection string 

     EntityConnectionStringBuilder entityString = new EntityConnectionStringBuilder() 
     { 
      Provider = "System.Data.SqlClient", 
      Metadata = "res://*/testModel.csdl|res://*/testModel.ssdl|res://*/testModel.msl", 
      ProviderConnectionString = sqlString.ToString() 
     }; 
     return entityString.ConnectionString; 
    } 
関連する問題