Reputation: 51
The main idea is to add a EF Core nuget package to a .NET Core library project and then use that library in a bunch of applications (e.g., ASP.NET Core, Win Service, Console App) without configuring EF in each of them. And, if possible, without adding EF packages to each of them. I'm wondering if it's possible.
My current problem is that I can't create a database based on the model I have in the library project.
It seems I can't just select the library project in the Package Manager Console and run update-database. It wants me to implement 'IDesignTimeDbContextFactory'.
I'm using .NET Core 2.1. Would it help if I update it to the latest version?
Upvotes: 4
Views: 1928
Reputation: 271
Yes, you can do this.
Make sure you have all the prerequisites installed.
public class Context
{
// See all queries generated by EF in debug window
public static readonly LoggerFactory MyLoggerFactory
= new LoggerFactory(new[] { new DebugLoggerProvider((s, level) => level >= LogLevel.Trace) });
public static DF.Data.Models.EF.YourContext GetContext()
{
var optionsBuilder = new DbContextOptionsBuilder<DF.Data.Models.EF.YourContext>();
optionsBuilder.UseSqlServer(
"Your Connection String").UseLoggerFactory(MyLoggerFactory);
return new DF.Data.Models.EF.YourContext(optionsBuilder.Options);
}
public partial class YourContext : DbContext
{
public YourContext(DbContextOptions optionsBuilderOptions) : base(optionsBuilderOptions)
{
}
}
}
Note: When you scaffold the database again make sure you select the Class library project as the default project from the dropdown. Then set your other project back to the startup project.
Upvotes: 2
Reputation: 6542
As mentioned by the error, you need to implement IDesignTimeDbContextFactory
which is part of the Microsoft.EntityFrameworkCore.Design
package so go ahead and install that in your library. Then create a class that implements IDesignTimeDbContextFactory
appropriately.
Since you created a .NET Core library, set that as your startup project.
Then in your Package Manager Console, select your library as the Default project and run update-database
.
Upvotes: 2