'How to make migrations from another project on a console application using .net6?
I am trying to execute the command add-migration with a console application which I made a context in a project apart from the console application, but when I Try to run it, it gives me the error, I am using .NET 6:
Unable to resolve service for type 'Microsoft.EntityFrameworkCore.Migrations.IMigrator'. This is often because no database provider has been configured for this DbContext. A provider can be configured by overriding the 'DbContext.OnConfiguring' method or by using 'AddDbContext' on the application service provider. If 'AddDbContext' is used, then also ensure that your DbContext type accepts a DbContextOptions<TContext> object in its constructor and passes it to the base constructor for DbContext.
Thats my context:
public class SchoolContext : DbContext
{
public DbSet<Student> Students { get; set; }
public DbSet<Course> Courses { get; set; }
public SchoolContext(DbContextOptions options) : base(options)
{
}
}
That's my main
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Persistencia;
var builder = new HostBuilder()
.ConfigureServices((hostContext, services) =>
{
services.AddLogging(configure => configure.AddConsole())
.AddDbContext<SchoolContext>(options =>
{
options.UseInMemoryDatabase( "testedb");
});
}).UseConsoleLifetime();
var host = builder.Build();
Project Structure Project Structure
Solution 1:[1]
The in-memory concept in meant to simulate your database in your memory (RAM). Migrations are used to generate/update your database schema to the connected database. The in-memory database doesn't need migrations. You can directly start your application and start using your DBContext without trying to add migrations.
But
If you need to migrate with SqlServer , you can follow this tutorial.
1 - Install this package on console app
Microsoft.EntityFrameworkCore.SqlServer
2 - change your AddDbContext like *"Shop.Console" is console project name.
more connection string options.
services.AddDbContext<ShopDbContext>(options =>
{
options
.UseSqlServer("Server=[server];Database=[name]; User ID = [if have]; Password = [if have];Trusted_Connection=false;MultipleActiveResultSets=true",
sqlServerOptionsAction: o => o.MigrationsAssembly("Shop.Console"));
});
3 - open Package Manager Console and run these commands
a- dotnet ef migrations add InitialContext -p "Shop.Console"
b- dotnet ef database update -p "Shop.Console"
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | thisisnabi |
