无法创建类型为“MyContext"的对象.对于设计时支持的不同模式 [英] Unable to create an object of type 'MyContext'. For the different patterns supported at design time

查看:24
本文介绍了无法创建类型为“MyContext"的对象.对于设计时支持的不同模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 .NET Core 上有 ConsoleApplication 并且我将我的 DbContext 添加到依赖项,但是我有一个错误:

I have ConsoleApplication on .NET Core and also i added my DbContext to dependencies, but howewer i have an error:

无法创建MyContext"类型的对象.有关设计时支持的不同模式,请参阅 https://go.microsoft.com/fwlink/?linkid=851728

Unable to create an object of type 'MyContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728

我添加了:var context = host.Services.GetRequiredService();我还添加了 private readonly DbContextOptions<MyContext>_opts; 在我的帖子类中:

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();
 }

这是我添加服务的方式:

This how i added service:

.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");
            }
        }

    }

我尝试添加迁移并出现此错误

I tried add-migration and has this error

我做错了什么?

推荐答案

我通过在我的上下文中添加一个普通的构造函数来解决这个问题

I Resolved this by just adding a plain constructor to my Context

public class DataContext : DbContext
{
    public DataContext()
    {
    }

    public DataContext(DbContextOptions options) : base(options)
    {
    }

    protected override void OnConfiguring(DbContextOptionsBuilder options)
    {
        if (!options.IsConfigured)
        {
            options.UseSqlServer("A FALLBACK CONNECTION STRING");
        }
    }
    
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);            
    }
}

这篇关于无法创建类型为“MyContext"的对象.对于设计时支持的不同模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆