繁体   English   中英

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

[英]Pass connection string to EF DbContext code first

我有一个从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.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的只读字符串中。 我只需要将类更新为:

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

我们必须指定实体连接字符串。 在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;
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM