首先将连接字符串传递给EF DbContext代码

时间:2017-04-13 17:11:39

标签: c# entity-framework ef-code-first dbcontext

我有一个派生自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;}
}

我正在尝试减少代码中静态的使用,因此,如果我能够获得第一个工作选项,那就太棒了。

2 个答案:

答案 0 :(得分:2)

原来,连接字符串缓存在MigrateDatabaseToLatestVersion enter image description here的只读字符串中。我只需将课程更新为:

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;} 
}

答案 1 :(得分:0)

我们必须指定实体连接字符串。在DbContext中

regex = re.compile('(?P<animal>\w+) (?P<verb>\w+) (?P<adjective>\w+)')