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

前端 未结 9 2998
逝去的感伤
逝去的感伤 2021-02-19 16:42

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 \'My

9条回答
  •  日久生厌
    2021-02-19 17:21

    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.

提交回复
热议问题