我在从具有多个DBContext的类库进行脚手架和迁移时遇到问题。我发现了一个迁移的命令行参数:
dnx ef migration add -c Contexts.IndustryContext initial
但这甚至不能通过命令行解析器。我希望我所有的DBContexts和数据库内容都来自主MVC 6 web项目,并在它们自己的DLL中。这可能吗?需要什么命令行魔术?
我一直在寻找这个问题的答案,并希望为ef core 2.0提供我的解决方案。
Microsoft.EntityFrameworkCore.Tools.DotNet
需要添加到每个包含DbContext
的类库中。在项目上单击鼠标右键,然后选择"Edit *.csproj
"。然后,添加以下内容:
<ItemGroup>
<DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="2.0.0-preview2-final" />
</ItemGroup>
注意:该版本是本文发布时的最新版本,将来可能会更改。
接下来,我创建了一个名为Migrations.Console的新控制台应用程序(.NET Core),并将其添加到我的解决方案中。在这个项目中,您必须引用所有的DbContext
类库。
我安装了Microsoft.EntityFrameworkCore
和Microsoft.EntityFrameworkCore.Design
Nuget软件包。
在Migrations.Console
应用程序中,我为我拥有的每个Db上下文创建了一个DbContextFactory类。
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
public class ApplicationDbContextFactory : IDesignTimeDbContextFactory<ApplicationDbContext>
{
public ApplicationDbContext CreateDbContext(string[] args)
{
var builder = new DbContextOptionsBuilder<ApplicationDbContext>();
builder.UseSqlServer("Server=(local);Database=DATABASENAME;Trusted_Connection=True;MultipleActiveResultSets=true");
return new ApplicationDbContext(builder.Options);
}
}
注意:请确保更新上下文和连接字符串以匹配您的项目。
现在创建了每个DbContextFactory
,就可以开始创建迁移了。转到类库的文件夹。最简单的方法是右键单击项目和Open Folder in File Explorer
。然后,在File Explorer
的地址栏中键入cmd
,打开该文件夹中的命令提示符。
现在使用以下命令创建迁移:
dotnet ef migrations add InitialCreate -c ApplicationDbContext --startup-project ../Migrations.Console/Migrations.Console.csproj
注意:更改ApplicationDbContext
以匹配正在使用的上下文的名称。此外,如果使用其他名称调用控制台项目,则需要更改路径和名称。
现在,您应该在类库中看到一个Migrations
文件夹。
我还没有尝试将数据层放在一个单独的项目中,但我在一个Web API项目中有多个DbContext。它也应该与单独的项目一起工作。
使用最新的语法(v1.0.0),您可以创建这样的迁移:
dotnet ef migrations add <migration-name> -o <output-directory> -c <context>
其中<context>
是DbContext的完整类名——类似于MyProject.Data.MyDbContext
我把针对不同上下文的迁移放在不同的目录中,但我认为你不必这么做。只需确保它们有不同的migration-name
值。
Usage: dnx ef dbcontext scaffold [arguments] [options]
Arguments:
[connection] The connection string of the database
[provider] The provider to use. For example, EntityFramework.MicrosoftSqlServer
Options:
-a|--data-annotations Use DataAnnotation attributes to configure the model where possible. If omitted, the output code will use only the fluent API.
-c|--context <name> Name of the generated DbContext class.
-o|--output-dir <path> Directory of the project where the classes should be output. If omitted, the top-level project directory is used.
-s|--schema <schema_name.table_name> Selects a schema for which to generate classes.
-t|--table <schema_name.table_name> Selects a table for which to generate classes.
-p|--target-project <project> The project to scaffold the model into. If omitted, the current project is used.
-e|--environment <environment> The environment to use. If omitted, "Development" is used.
-v|--verbose Show verbose output
-?|-h|--help Show help information