[英]Unable to create an object for DataContext
I am trying to run the migration in order to create sqlite DB in .net core 6. But getting the following error我正在尝试运行迁移,以便在 .net 核心 6 中创建 sqlite 数据库。但出现以下错误
Unable to create an object for DataContext.For different patterns supported at design time.无法为 DataContext 创建 object。对于设计时支持的不同模式。
appsettings.json file code appsettings.json 文件代码
{
"ConnectionStrings": {
"DefaultConnection": "Data source=UrlDB.db"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}
DataContext class code DataContext class代码
public class DataContext : DbContext
{
public DataContext(DbContextOptions options) : base(options)
{
}
public DbSet<UrlTbl> UrlTbl { get; set; }
}
I also created an extension class just to keep my code clean.我还创建了一个扩展 class 只是为了保持我的代码干净。 and in this class, I have an extension method to addDbConext into services.在这个 class 中,我有一个扩展方法可以将 DbConext 添加到服务中。 Here is the code of that class这是 class 的代码
public static class ApplicationServicesExtension
{
public static IServiceCollection AddApplicationServices(this IServiceCollection _services, IConfiguration _config)
{
_services.AddDbContext<DataContext>(options =>
{
options.UseSqlite(_config.GetConnectionString("DefaultConnection"));
});
return _services;
}
}
and I am accessing this extension method in Programme.cs in this way我正在以这种方式访问 Programme.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();
Try changing your DataContext
to this:尝试将您的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; }
}
Update your ApplicationServicesExtension
to:将您的ApplicationServicesExtension
更新为:
public static class ApplicationServicesExtension
{
public static IServiceCollection AddApplicationServices(this IServiceCollection services)
{
services.AddDbContext<DataContext>();
return services;
}
}
In your Program.cs
在你的Program.cs
...
builder.Services.AddApplicationServices();
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.