/ / Entity Framework 7-移行:移行のためだけにデータベースプロバイダーと接続文字列を指定する方法-entity-framework

Entity Framework 7 - 移行:移行のためだけにデータベースプロバイダと接続文字列を指定する方法 - entity-framework

どの方法を指定する方法はありますかDataProvider(SQL Server)とConnectionStringは、移行の生成(Add-Migration)とデータベースの更新(Update-Database)にのみ使用しますか?データプロバイダーの選択と接続文字列の読み込みをDbContext(.UseSqlServer())にハードコーディングしたくありません。

EF6はweb.configから直接接続文字列を選択できると思いますが、EF7に似たようなものはありますか?

回答:

回答№1は1

いいえ、optionsBuilderを使用する必要はありません。

例:

string oldConnectionString =@"Server = .;Initial Catalog=EFTutorial; AttachDbFilename=|DataDirectory|EFTutorial.mdf; Trusted_Connection = True; MultipleActiveResultSets = true";

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(oldConnectionString );
base.OnConfiguring(optionsBuilder);
}

jsonとしてロードし、app.configまたはweb.configから直接ロードすることもできます。

.Net Coreを使用している場合:

appsettings.jsonで、接続文字列を次のように定義できます。

{
{
....

},
"Data": {
"ConnectionString": "..."
}
}

アプリの起動時にロードする必要があります:

// Set up configuration sources.
var builder = new ConfigurationBuilder().AddJsonFile("appsettings.json");
builder.AddEnvironmentVariables();
Configuration = builder.Build().ReloadOnChanged("appsettings.json");

その後、Startup.csでEntityFrameworkも構成する必要があります。

public void ConfigureServices(IServiceCollection services)
{
...
services.AddEntityFramework()
.AddSqlServer()
.AddDbContext<AppContext>(options =>
{
options.UseSqlServer(Configuration "Data:ConnectionString"]); });
services.AddScoped<AppContext, AppContext>();

...
}
}

ここで重要なこと:

services.AddScoped((_) => new AppContext(Configuration["Data:DefaultConnection:ConnectionString"]));

https://docs.asp.net/en/latest/data/entity-framework-6.html

Entity Framework Core 1.0 / 7の接続文字列の例: https://docs.asp.net/en/latest/fundamentals/configuration.html

古い方法(EFコアでも可能です)App.configまたはweb.configからconenctionStringをロードしました 移行プロセスのAdd-Migration / Update-Databaseによって、EFは接続文字列を自動的に検出します。 ただし、NuGetコマンド行のAdd-Migrationに接続文字列をパラメーターとして指定することもできます。

これで問題が解決することを願っています!