I'm new to WinUI3
and want to use EntityFrameworkCore
to my project.
I have configured my DbContext
like all of my other projects:
public class BusinessDomainContext : DbContext
{
public DbSet<Subject> Subjects { get; set; }
public DbSet<Test> Tests { get; set; }
public BusinessDomainContext(DbContextOptions<BusinessDomainContext> options) : base(options) { }
}
At the next step, I added Dependency Injection
by reading the Microsoft
manuals.
So I have an App.Xaml.cs
that looks like below:
public App()
{
ConfigureServices();
this.InitializeComponent();
}
private static IServiceProvider ConfigureServices()
{
var services = new ServiceCollection();
SetupLogger(services);
string businessDomainConnection = ConfigurationManager.AppSettings["BusinessDomainConnectionString"];
services.AddDbContext<BusinessDomainContext>(options =>
{
options.UseSqlServer(businessDomainConnection);
});
return services.BuildServiceProvider();
}
Now I tried to run Add-Migration
command.
Add-Migration InitialCreate -Context BusinessDomainContext -OutputDir Migrations\BusinessDomain
It fails on this error:
Unable to create an object of type 'BusinessDomainContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728
I couldn't found a descriptive solution for this.
My feasible way of doing this was to create an separated console application using this document, and run Add-Migration
while it was set as startup project
.
Is there any better solution for this ?
You need to look at this: https://learn.microsoft.com/en-us/ef/core/cli/dbcontext-creation?tabs=dotnet-core-cli#from-a-design-time-factory
public class BusinessDomainContextFactory : IDesignTimeDbContextFactory<BusinessDomainContext>
{
public BusinessDomainContext CreateDbContext(string[] args)
{
var optionsBuilder = new DbContextOptionsBuilder<BloggingContext>();
optionsBuilder.UseSqlServer("ConnectionString");
return new BusinessDomainContext(optionsBuilder.Options);
}
}