在 .NETStandard 库项目中执行 EFcore 迁移

Executing EFcore Migrations inside a .NETStandard Library project

我的问题基本上是:是否可以在 .NET Standard 2.0 库项目中使用 Entity Framework 核心(和迁移)? (不是核心项目)

我目前有 2 个项目:

对于 .NETStandard DAL 项目,我使用以下设置和 类:.csproj 文件包含 EF 和迁移的依赖项:

<ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="2.0.0" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="2.0.0" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="2.0.0" />
</ItemGroup>

<ItemGroup>
    <DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="2.0.0" />
</ItemGroup>

调用dotnet restore后,我创建了一个DbContext后代:

class MyTestContext: DbContext
{
    public MyTestContext(DbContextOptions<MyTestContext> options) : base(options)
    {
    }

    public DbSet<Class1> Class1Table { get; set; }
}

并添加了 DbContextFactoryIDesignTimeDbContextFactory,例如:

class DbContextFactory : IDesignTimeDbContextFactory<MyTestContext>
{
    public MyTestContext CreateDbContext(string[] args)
    {
        var builder = new DbContextOptionsBuilder<MyTestContext>();
        builder.UseSqlServer("Server=(localdb)\mssqllocaldb;Database=efmigrations2017;Trusted_Connection=True;MultipleActiveResultSets=true",
            optionsBuilder => optionsBuilder.MigrationsAssembly(typeof(MyTestContext).GetTypeInfo().Assembly.GetName().Name));

        return new MyTestContext(builder.Options);
    }
}

好的,到目前为止一切正常,.NETStandard 项目构建成功。

现在我想通过执行来创建我的第一个迁移:

dotnet ef migrations add InitialCreate

这会引发错误:

如果我对错误消息的理解正确,EF Core 只能用于 .NET Core 和 .NET Framework 项目,NOT 用于 .NETStandard 项目?

如果是这样,我如何将 EF 数据库逻辑与我的其他应用程序分开?

如果没有,我怎样才能使迁移工作?

提前致谢

你有两个选择。

一:使用你的ASP.NET核心项目作为启动项目。

dotnet ef migrations add InitialCreate --startup-project ..\MyWebApplication

二:class 库中的跨目标 .NET Core。 (编辑*.csproj)

<PropertyGroup>
  <!-- Note: This property name becomes plural. -->
  <TargetFrameworks>netcoreapp2.0;netstandard2.0</TargetFrameworks>
</PropertyGroup>