我正在 ASP.NET Core 2.0 中构建应用程序,但在 EntityFramework 迁移方面遇到问题。
我的 DbContext 位于一个单独的项目中(解决方案名称\项目名称前缀.Data),因此我创建了 IDesignTimeDbContextFactory 接口的实现。
我想为不同的环境使用不同的连接字符串,我需要appsettings.json
为了那个原因。
因此,经过快速搜索后,我发现我可以创建一个新的IConfigurationRoot
里面的物体CreateDbContext
函数如下所示:https://codingblast.com/entityframework-core-idesigntimedbcontextfactory/ https://codingblast.com/entityframework-core-idesigntimedbcontextfactory/
我添加了它,然后为了测试,尝试运行dotnet ef migrations list -c MyContext
从数据项目根文件夹。
然后我收到以下错误:
The configuration file 'appsettings.json' was not found and is not optional. The physical path is 'C:\dev\*SolutionName*\*ProjectNamePrefix*.Data\bin\Debug\netcoreapp2.0\appsettings.json'.
所以,基本上,我尝试了 3 个选项来获取正确的根路径:
Directory.GetCurrentDirectory();
-
env.ContentRootPath;
(IHostingEnvironment
对象,我找到了一种方法来获取它:https://github.com/aspnet/Home/issues/2194 https://github.com/aspnet/Home/issues/2194)
AppDomain.CurrentDomain.BaseDirectory;
他们都返回相同的..\bin\debug\netcoreapp2.0\
小路。当我从 VS 运行数据项目时,前两个选项为我提供了正确的项目根文件夹。
有没有办法获取正确的项目内容根文件夹?
因为当我向 EF 命令添加 --verbose 时,它会注销一行:
Using content root 'C:\dev\FitsMeIdentity\FitsMeIdentity.Data\'.
所以我知道 EF 以某种方式知道项目根目录,但上面提到的所有选项都会返回已构建的应用程序的路径。
我发现唯一有效的选择是我改变Copy output to root folder
to Copy always
但从这里发现:https://www.benday.com/2017/02/17/ef-core-migrations-without-hard-coding-a-connection-string-using-idbcontextfactory/ https://www.benday.com/2017/02/17/ef-core-migrations-without-hard-coding-a-connection-string-using-idbcontextfactory/这不是一个好主意。
起初,我什至考虑为 IDesignTimeDbContextFactory 实现创建一个构造函数,它将 IOptions 作为参数,但这不起作用,有与此处解释的相同的问题:将 Env Conn 字符串注入到 .NET Core 2.0 w/EF Core DbContext 中,位于与 Startup prj 不同的类库中并实现 IDesignTimeDbContextFactory https://stackoverflow.com/questions/46085500/injecting-env-conn-string-into-net-core-2-0-w-ef-core-dbcontext-in-different-cl