[英]Entity Framework Core Unable to create an object of type 'DbContext'. Error
I am building an n-tier web api with .net 6 using cqrs and mediatr patterns.我正在使用 .net 6 使用 cqrs 和 mediatr 模式构建一个 n 层 web api。
But i am getting the following exception when i want to add first migration.但是当我想添加第一次迁移时出现以下异常。
Unable to create an object of type 'WorldCupApiDbContext'.
无法创建“WorldCupApiDbContext”类型的对象。 For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728
有关设计时支持的不同模式,请参阅https://go.microsoft.com/fwlink/?linkid=851728
This is what my solution looks like:这是我的解决方案的样子:
My Program.cs codes:我的 Program.cs 代码:
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:我的 DbContext 代码:
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.我尝试按如下方式编辑 DbContext 寄存器,但不起作用。
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-cli,只需在终端中输入:
dotnet ef migrations add MigrationName -s mainProject -p DbContextProject
dotnet ef migrations add MigrationName -s mainProject -p DbContextProject
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.