无法创建类型为 'MyContext' 的对象。针对设计时支持的不同模式

31
我有一个基于.NET Core的ConsoleApplication,并将我的DbContext添加到了依赖项中,但是我仍然遇到了错误:
无法创建类型为'MyContext'的对象。有关在设计时支持的不同模式,请参见https://go.microsoft.com/fwlink/?linkid=851728 我已经添加了:var context = host.Services.GetRequiredService<MyContext>(); 同时,在我的Post类中,我还添加了private readonly DbContextOptions<MyContext> _opts;
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命令,但出现了错误

我做错了什么?

20个回答

1

请确保您已在Startup类中将DbContext添加到服务中


1
如果你使用的是 macOS 平台,你必须设置启动项目。
 dotnet ef --startup-project ../NLayer.API/ migrations add Initial

数据库更新用途
dotnet ef --startup-project ../NLayer.API/ database update

0
在我的情况下,使用Net Core 3.1(PostgreSQL),通过删除“AddUserStore”解决了这个问题。
 services.AddIdentity<User, IdentityRole<int>>()
                .AddEntityFrameworkStores<MyDBContext>()
                //.AddUserStore<MyDBContext>()
                .AddDefaultTokenProviders();

0
在我的情况下,我的解决方案中有两个启动项目,因此将具有连接字符串的项目设置为唯一的启动项目解决了这个问题。

0
我在.NET 6中遇到了这个问题。在program.cs文件中,您应该在Services.AddDbContextconnectionString之后放置var app = builder.Build();

0
  1. 在我的情况下,我的数据库连接字符串是错误的,我提供了错误的数据库密码,导致了这个问题。因此,请检查您在appsettings.json中的连接字符串。
  2. 确保将您的Web或API项目设置为“设置为启动项目”。不要使用多个启动项目。
  3. 在程序包管理器控制台中,将您的数据访问层(如果有)设置为默认项目
  4. 然后再次运行命令

0

如果有人仍在使用这种方法来了解为什么会出现此错误。

这是因为表的键或约束的配置存在错误。

您可以使用dotnet ef database update --verbose命令,以了解迁移时生成的错误。


0
我通过以下方式解决了这个问题:
    public DbSet<PostData> Posts { get; set; }
    public DbSet<VoteData> Votes { get; set; }

    public MyContext(DbContextOptions options) : base(options) { Database.EnsureCreated(); }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.ApplyConfigurationsFromAssembly(typeof(MyContext).Assembly);
    }

0
你需要将这段代码添加到Program.cs文件中。
builder.Services.AddDbContext<DataContext>(options => {
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")); });

这是 appsettings.json

"ConnectionStrings": {
"DefaultConnection" :  "server=localhost\\sqlexpress;database=superherodb;trusted_connection=true"  },

0
我在我的项目中遇到了同样的问题。我忘记在我的Program.cs文件中添加DbContext。我添加了以下代码,问题得到了解决:
builder.Services.AddDbContext<DataContext>(options =>
{
    options.UseSqlServer(builder.Configuration
        .GetConnectionString("DefaultConnection"));
});

在我的 "Program.cs" 文件中的屏幕截图 1 而在我的 "appsettings.json" 文件中:
"ConnectionStrings": {
"DefaultConnection": "Data Source=YOUR_SERVER_HERE;Initial Catalog=YOUR_DB_HERE;Integrated Security=True"

}


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接