Programmatically change path for EF Core database in console project

那年仲夏 提交于 2019-12-12 02:25:59

问题


I'm using EF Core, to manage a SQLite database file, in a console project.

When I create a database, the file is created in the bin folder, so basically MyProjectName\bin\Debug\netcoreapp1.1\FooDatabase.sqlite.

I want to change this.

I tried setting Directory.SetCurrentDirectory and IHostingEnvironment.ContentRootPath. Nothing works.

How do I programmatically set the directory that the database should be created in?


回答1:


In Microsoft.Data.Sqlite 2.0 (not yet released), Directory.SetCurrentDirectory() will do the trick.

Until then I suggest using an absolute path in your connection string:

var builder = new SqliteConnectionStringBuilder(relativeConnectionString);
bilder.DataSource = Path.Combine(dataDirectory, bilder.DataSource);
var absoluteConnectionString = builder.ToString();

If you really want to fiddle with the internal mechanics, you can, but I wouldn't recommend it:

// .NET Framework
AppDomain.CurrentDomain.SetData("DataDirectory", myDataDirectory);

// .NET Core
Environment.SetEnvironmentVariable("ADONET_DATA_DIR", myDataDirectory);


来源:https://stackoverflow.com/questions/42541767/programmatically-change-path-for-ef-core-database-in-console-project

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!