无法为DataContext创建对象



我正试图运行迁移,以便在。net core 6中创建sqlite DB。但是得到以下错误

无法为DataContext创建对象。不同的模式在设计时支持。

appsettings。Json文件代码

{
"ConnectionStrings": {
"DefaultConnection": "Data source=UrlDB.db"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}

DataContext类代码

public class DataContext : DbContext
{
public DataContext(DbContextOptions options) : base(options)
{
}
public DbSet<UrlTbl> UrlTbl { get; set; }
}

我还创建了一个扩展类只是为了保持我的代码整洁。在这个类中,我有一个扩展方法来添加dbcontext到服务中。下面是该类

的代码
public static class ApplicationServicesExtension
{
public static IServiceCollection AddApplicationServices(this IServiceCollection _services, IConfiguration _config)
{
_services.AddDbContext<DataContext>(options =>
{
options.UseSqlite(_config.GetConnectionString("DefaultConnection"));
});
return _services;
}
}

,我在program .cs中以这种方式访问这个扩展方法

using UrlEntryApp.Extensions;
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
IConfiguration _config=app.Configuration;
// Add services to the container.
builder.Services.AddControllers();
builder.Services.AddApplicationServices(_config);
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

尝试更改您的DataContext:

public class DataContext : DbContext
{
protected readonly IConfiguration Configuration;
public DataContext(IConfiguration configuration)
{
Configuration = configuration;
}
protected override void OnConfiguring(DbContextOptionsBuilder options)
{
// connect to sql server database
options.UseSqlite(Configuration.GetConnectionString("DefaultConnection"));
}
public DbSet<UrlTbl> UrlTbl { get; set; }
}

更新你的ApplicationServicesExtension到:

public static class ApplicationServicesExtension
{
public static IServiceCollection AddApplicationServices(this IServiceCollection services)
{
services.AddDbContext<DataContext>();
return services;
}
}

在你的Program.cs

...
builder.Services.AddApplicationServices();
...

最新更新