Reputation: 2214
I thought it would be nice to move my database classes out of a NET.Core project into a class library.
I had a class called ApiRegistrationDataContext
, inheriting from DbContext
and a class ApiRegistrationSqliteDataContext
, inheriting from ApiRegistrationDataContext
.
In the ASP.Core-project I had some lines regarding the database classes in file Startup.cs
and in a service. I would create a migration via Add-Migration SomeName -Context ApiRegistrationSqliteDataContext -OutputDir Migrations\ApiRegistrationSqliteMigrations
.
Now I moved those classes into a class library and removed all connections from the ASP.Core project. However now I cannot create a new Migration (I was able to move the old migration from the ASP.Core project to the class library).
The error message reads
Unable to create an object of type 'ContactDataContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728
which is honestly no help at all. Why did it work in the ASP.Core project but not in my class library anymore?
Upvotes: 1
Views: 1639
Reputation: 141565
As docs state:
Some of the EF Core Tools commands (for example, the Migrations commands) require a derived DbContext instance to be created at design time in order to gather details about the application's entity types and how they map to a database schema.
So after your changes EF can't do it. One of the options would be to create IDesignTimeDbContextFactory
inside of the corresponding project:
public class ApiRegistrationSqliteDataContextContextFactory : IDesignTimeDbContextFactory<ApiRegistrationSqliteDataContext>
{
public ApiRegistrationSqliteDataContext CreateDbContext(string[] args)
{
var optionsBuilder = new DbContextOptionsBuilder<ApiRegistrationSqliteDataContext>();
optionsBuilder.UseSqlite("Data Source=blog.db");
return new ApiRegistrationSqliteDataContext(optionsBuilder.Options);
}
}
Also if you are using VS package manager console to work with migrations make sure that you have set correct startup project (in solution explorer) and default project (in package manager console).
Also try to run Add-Migration specifying Verbose
flag:
Add-Migration SomeName -Context ApiRegistrationSqliteDataContext -OutputDir Migrations\ApiRegistrationSqliteMigrations -Verbose
Upvotes: 1