我在 .NET Core 上有 ConsoleApplication 并且我将我的 DbContext 添加到依赖项中,但是我有一个错误:
无法创建类型为“MyContext”的对象。有关设计时支持的不同模式,请参阅https://go.microsoft.com/fwlink/?linkid=851728
我添加了:var context = host.Services.GetRequiredService<MyContext>();
我private readonly DbContextOptions<MyContext> _opts;还在我的帖子类中添加了:
using (MyContext db = new MyContext(_opts))
{
db.Posts.Add(postData);
db.SaveChanges();
}
Run Code Online (Sandbox Code Playgroud)
这是我添加服务的方式:
.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));
Run Code Online (Sandbox Code Playgroud)
这是我的上下文:
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 …Run Code Online (Sandbox Code Playgroud) 当我使用实体框架时,我有简单的 WPF Net Core 应用程序,我有 DbContext,但是当我添加迁移时,我收到错误:
PM> add-migration init
Build started...
Build succeeded.
Unable to create an object of type 'AppDbContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728
Run Code Online (Sandbox Code Playgroud)
我的应用程序设置.json
{
"ConnectionStrings": {
"SqlConnection": "Server=DESKTOP-K6R1EB3\\tester;Database=test;Trusted_Connection=True;MultipleActiveResultSets=true"
}
}
Run Code Online (Sandbox Code Playgroud)
应用程序数据库上下文
using Microsoft.EntityFrameworkCore;
namespace WpfApp1
{
public class AppDbContext : DbContext
{
public DbSet<Person> Person { get; set; }
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
{
}
}
}
Run Code Online (Sandbox Code Playgroud)
应用程序.xaml.cs
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.IO;
using System.Windows; …Run Code Online (Sandbox Code Playgroud)