问题描述
我在.NET Core上具有ConsoleApplication,并且还向依赖项中添加了DbContext,但是我却遇到了错误:
I have ConsoleApplication on .NET Core and also i added my DbContext to dependencies, but howewer i have an error:
我添加了: var context = host.Services.GetRequiredService< ; MyContext>();
另外,我还添加了 private只读DbContextOptions< MyContext> _opts;
在我的Post类中:
i've added: var context = host.Services.GetRequiredService<MyContext>();
Also i've added private readonly DbContextOptions<MyContext> _opts;
in my Post Class:
using (MyContext db = new MyContext(_opts))
{
db.Posts.Add(postData);
db.SaveChanges();
}
我如何添加服务:
.ConfigureServices((context, services) =>
{
services.Configure<DataOptions>(opts =>
context.Configuration.GetSection(nameof(DataOptions)).Bind(opts));
services.AddDbContext<MyContext>((provider, builder) =>
builder.UseSqlite(provider.GetRequiredService<IOptions<DataOptions>>().Value.ConnectionString));
这是我的上下文:
public sealed class MyContext : DbContext
{
private readonly DbContextOptions<MyContext> _options;
public DbSet<PostData> Posts { get; set; }
public DbSet<VoteData> Votes { get; set; }
public MyContext(DbContextOptions<MyContext> options) : base(options)
{
_options = options;
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
optionsBuilder.UseSqlite("ConnectionString");
}
}
}
add-migration并出现此错误
I tried add-migration and has this error
我做错了什么?
推荐答案
NET Core 3.0 ,并且要解决该问题,必须将 IHostBuilder 更改为 IWebHost ,然后一切都很好。问题出在Program类中。
I've had same problem as You. Maybe it was not for a Console Application but error was the same. So i thought that it is worth to share with my answer. I was using NET Core 3.0 and to fix the problem I have to change the IHostBuilder into IWebHost and then everything was fine. The problem was in class Program.
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
进入
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
这篇关于无法创建类型为“ MyContext”的对象。针对设计时支持的不同模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!