我有一个从派生的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;}
}
我试图减少使用静态的代码,因此,如果我能得到工作的第一个选项,那简直太好了。