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