I am building an n-tier web api with .net 6 using cqrs and mediatr patterns.
But i am getting the following exception when i want to add first migration.
Unable to create an object of type 'WorldCupApiDbContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728
This is what my solution looks like:
My Program.cs codes :
using System.Reflection;
using MediatR;
using Microsoft.EntityFrameworkCore;
using WorldCupApi.Application.Handler.QueryHandler;
using WorldCupApi.Repository.Entities;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddDbContextPool<WorldCupApiDbContext>(options =>
{
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"));
});
builder.Services.AddMediatR(typeof(GetGroupQueryHandler).GetTypeInfo().Assembly);
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
My DbContext codes :
using Microsoft.EntityFrameworkCore;
namespace WorldCupApi.Repository.Entities;
public class WorldCupApiDbContext : DbContext
{
public WorldCupApiDbContext(DbContextOptions<WorldCupApiDbContext> options) : base(options)
{
}
//entities
public DbSet<Group> Groups { get; set; }
public DbSet<Team> Teams { get; set; }
}
I tried editing the DbContext register as follows but doesn't work.
builder.Services.AddDbContextPool<WorldCupApiDbContext>(options =>
{
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"),
b=> b.MigrationsAssembly("WorldCupApi.Repository"));
});
If you need more details, I can send them quickly. Please help me.
I solved the problem. I would like to share with you too.
if you use dotnet-cli just type this in terminal:
dotnet ef migrations add MigrationName -s mainProject -p DbContextProject