通过动态数据库连接在Entity Framework Core中添加迁移

时间:2019-04-13 10:41:53

标签: .net-core entity-framework-core ef-migrations

我正在使用Entity Frameowrk Core处理.NET Core 3.0 WPF应用程序中的不同数据库。我为不同的用户使用了不同的SQLite DB文件,因此每个登录的用户的连接字符串都会更改。

我必须能够使用迁移,但是例如,当我运行dotnet ef migrations add V2时,它会失败,因为它找不到数据库。

在这种情况下如何生成迁移?

这是我的上下文代码:

protected override void OnConfiguring(DbContextOptionsBuilder options)
{
      var connectionString = string.Format("Data Source={0}", GetDbPath(this.username));

      this.connection = new SqliteConnection(connectionString);
      this.connection.Open();

      options.UseSqlite(this.connection)
}

1 个答案:

答案 0 :(得分:0)

最后,我找到了一种解决方法,可以在生成迁移时临时使用固定的本地DB路径,因此不会因丢失变量而出现运行时错误:

// var dbPath = GetDbPath(this.username);
var dbPath = "C:\\DB.db";
var connectionString = string.Format("Data Source={0}", dbPath);
...