在控制台项目中以编程方式更改EF Core数据库的路径 [英] Programmatically change path for EF Core database in console project

查看:146
本文介绍了在控制台项目中以编程方式更改EF Core数据库的路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用EF Core在一个控制台项目中管理SQLite数据库文件。

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

创建数据库时,该文件是在bin中创建的文件夹,因此基本上是 MyProjectName\bin\Debug\netcoreapp1.1\FooDatabase.sqlite

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

我想更改它。

我尝试设置 Directory.SetCurrentDirectory IHostingEnvironment.ContentRootPath 。没什么用。

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

如何以编程方式设置应在其中创建数据库的目录?

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

推荐答案

Microsoft.Data.Sqlite 2.0(尚未发布)中, Directory.SetCurrentDirectory()

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

这篇关于在控制台项目中以编程方式更改EF Core数据库的路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆