Unable to create an object of type 'MyContext'. For the different patterns supported at design time

 ̄綄美尐妖づ 提交于 2020-05-26 11:18:08

问题


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

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

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

And this is my Context:

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

What i do wrong?


回答1:


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

into

public static void Main(string[] args)
    {
        BuildWebHost(args).Run();
    }

    public static IWebHost BuildWebHost(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .UseStartup<Startup>()
        .Build();



回答2:


Kindly check your connection string also in appsetting,json.




回答3:


The quick solution to the problem is to implement the default constructor in your context

 public MyContext() : base()
 {
 }

The problem with this solution is that you will have to enter the connection string in the 'OnConfiguring' function explicitly, which is not recommended

 protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
 {
        if (!optionsBuilder.IsConfigured)
        {
            optionsBuilder.UseSqlite("ConnectionString");
        }
 }



回答4:


This applies to ASP .NET or .NET console applications using .NET Core 3.1.

In my case it was ASPNET Core and I had the same reported problem after upgrading my application from 2.1 to 3.1. The answer provided by @Matt lead me to a solution that works and allows me to continue using the new Generic Host. The Web Host remains only for backward compatibility.

The documentation for Generic Host and Design-time DbContext Creation both state what needs to happen.

Your program.cs must have a CreateHostBuilder method with a signature exactly as documented. This is because the framework attempts to resolve it using Program.CreateHostBuilder(). The signature must be:

public static IHostBuilder CreateHostBuilder(string[] args)

This is what caught me out, I initially had it named CreateWebHostBuilder, a 2.1 convention; and then I didn't have the args parameter defined. Fixing these two issues immediately resolved my add-migration ... error.

The Design-time DbContext Creation documentation is quite helpful detailing how the framework attempts to resolve the DbContext and explains why other suggestions here work the way they do, e.g. parameterless constructor.




回答5:


In my case, I had two startup project in my solution, so setting the project that has the connection string as the only startup project fixed the issue



来源:https://stackoverflow.com/questions/57745481/unable-to-create-an-object-of-type-mycontext-for-the-different-patterns-suppo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!