My question is basically: is it possible to use Entity Framework Core (and migrations) inside a .NET Standard 2.0 library project? (not a core project)
I currently have 2 projects:
ASP.NET Core main project: I don't want anything with databases or EF inside this project, so I added a reference to the .NETstandard2.0 DAL project
.NETStandard2.0 data access layer project: EF Core with database migrations project for accessing the database. The main project uses this project to get data from the database.
For the .NETStandard DAL project, I use the following settings and classes: the .csproj
file contains the dependencies for EF and migrations:
<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>
After calling dotnet restore
, I created a DbContext
descendant:
class MyTestContext: DbContext
{
public MyTestContext(DbContextOptions<MyTestContext> options) : base(options)
{
}
public DbSet<Class1> Class1Table { get; set; }
}
And added a DbContextFactory
with IDesignTimeDbContextFactory
like:
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);
}
}
Okay, so far everything works fine and the .NETStandard project builds successfully.
Now I want to create my first migration by executing:
dotnet ef migrations add InitialCreate
This throws an error:
If I understand the error message correctly, EF Core can only be used in .NET Core and .NET Framework projects and NOT in .NETStandard projects?
If that is true, how can I separate the EF database logic from my other applications?
If not, how can I get the migrations to work?
Thank you in advance
You can use EF Core in APIs and applications that require the full . NET Framework, as well as those that target only the cross-platform .
You have two options.
One: Use your ASP.NET Core project as the startup project.
dotnet ef migrations add InitialCreate --startup-project ..\MyWebApplication
Two: Cross-target .NET Core in your class library. (Edit the *.csproj
)
<PropertyGroup>
<!-- Note: This property name becomes plural. -->
<TargetFrameworks>netcoreapp2.0;netstandard2.0</TargetFrameworks>
</PropertyGroup>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With