通连接字符串EF的DbContext代码首先
问题描述:
我有一个从派生的DbContext类似下面的上下文:通连接字符串EF的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,我也尝试过使用this.Database.Connection.ConnectionString在StudentContext构造函数中设置连接字符串。无论哪种情况,我都会得到一个异常,要求我提供一个默认构造函数或提供一个实现的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;}
}
我试图减少使用静态的代码,因此,如果我能得到工作的第一个选项,那简直太好了。
答
原来,连接字符串缓存在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;}
}
答
我们必须指定实体连接字符串。 in 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;
}