efcore: Cannot make migration. ef core 2.0
I’ve migrated from .NET Core 1.1 to .NET Core 2.0. Have some troubles with EF Core 2.0. I’m using multi environment. dotnet-ef command missing -e (environment) option, that is required in my project.
dotnet ef migrations add Test -c BackendContext -v
Error
Using project \Backend.csproj'.
Using startup project \Backend.csproj'.
Writing '\obj\Backend.csproj.EntityFrameworkCore.targets'...
dotnet msbuild /target:GetEFProjectMetadata /property:EFProjectMetadataFile=C:\Users\user\AppData\Local\Temp\tmpE244.tmp /verbosity:quiet /nologo \Backend.csproj
Writing '\obj\Backend.csproj.EntityFrameworkCore.targets'...
dotnet msbuild /target:GetEFProjectMetadata /property:EFProjectMetadataFile=C:\Users\user\AppData\Local\Temp\tmpE468.tmp /verbosity:quiet /nologo \Backend.csproj
dotnet build \Backend.csproj /verbosity:quiet /nologo
Build succeeded.
0 Warning(s)
0 Error(s)
Time Elapsed 00:00:03.33
dotnet exec --depsfile \bin\Debug\netcoreapp2.0\Backend.deps.json --additionalprobingpath C:\Users\user\.nuget\packages --additionalprobingpath "C:\Program Files\dotnet\sdk\NuGetFallbackFolder" --runtimeconfig \bin\Debug\netcoreapp2.0\Backend.runtimeconfig.json C:\Users\user\.nuget\packages\microsoft.entityframeworkcore.tools.dotnet\2.0.0\tools\netcoreapp2.0\ef.dll migrations add Test -c BackendContext --assembly \bin\Debug\netcoreapp2.0\Backend.dll --startup-assembly \bin\Debug\netcoreapp2.0\Backend.dll --project-dir \ --verbose --root-namespace Backend
Using assembly 'Backend'.
Using startup assembly 'Backend'.
Using application base \bin\Debug\netcoreapp2.0'.
Using working directory '\'.
Using root namespace 'Backend'.
Using project directory '\'.
Finding DbContext classes...
Finding IDesignTimeDbContextFactory implementations...
Finding application service provider...
Finding BuildWebHost method...
No BuildWebHost method was found on type 'Backend.Program'.
No application service provider was found.
Finding DbContext classes in the project...
Found DbContext 'BackendContext'.
Found DbContext 'LiteContext'.
Microsoft.EntityFrameworkCore.Design.OperationException: Unable to create an object of type 'BackendContext'. Add an implementation of 'IDesignTimeDbContextFactory<BackendContext>' to the project, or see https://go.microsoft.com/fwlink/?linkid=851728 for additional patterns supported at design time. ---> System.MissingMethodException: No parameterless constructor defined for this object.
at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor)
at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark)
at System.Activator.CreateInstance(Type type, Boolean nonPublic)
at System.Activator.CreateInstance(Type type)
at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.<>c__DisplayClass12_3.<FindContextTypes>b__13()
--- End of inner exception stack trace ---
at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.<>c__DisplayClass12_3.<FindContextTypes>b__13()
at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(Func`1 factory)
at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(String contextType)
at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.AddMigration(String name, String outputDir, String contextType)
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigrationImpl(String name, String outputDir, String contextType)
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigration.<>c__DisplayClass0_1.<.ctor>b__0()
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.<>c__DisplayClass3_0`1.<Execute>b__0()
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
Unable to create an object of type 'BackendContext'. Add an implementation of 'IDesignTimeDbContextFactory<BackendContext>' to the project, or see https://go.microsoft.com/fwlink/?linkid=851728 for additional patterns supported at design time.
BackendContext
public class BackendContext : DbContext
{
public BackendContext(DbContextOptions<BackendContext> options)
: base(options)
{ }
}
In Startup.cs
services.AddDbContext<BackendContext>(opts =>
opts.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
EF Core version: 2.0 Database Provider: Microsoft.EntityFrameworkCore.SqlServer Operating system: win10-x64 IDE: Visual Studio 2017 .NET Core SDK info:
.NET Command Line Tools (2.0.0)
Product Information:
Version: 2.0.0
Commit SHA-1 hash: cdcd1928c9
Runtime Environment:
OS Name: Windows
OS Version: 10.0.15063
OS Platform: Windows
RID: win10-x64
Base Path: C:\Program Files\dotnet\sdk\2.0.0\
Microsoft .NET Core Shared Framework Host
Version : 2.0.0
Build : e8b8861ac7faf042c87a5c2f9f2d04c98b69f28d
About this issue
- Original URL
- State: closed
- Created 7 years ago
- Comments: 48 (6 by maintainers)
@Sweetog look at paragraph
dotnet ef database updateand there is a comment:So you just need to update your Program.cs to:
Changing Program.cs to one quoted in the article fixed the error for me. No
IDesignTimeDbContextFactoryneeded.Here is my context:
Scenario 1 - old way of Program.cs
…and migration (I use -s because I have all my DB stuff in separate project):
Scenario2 - new way of Project.cs
Just one change here:
…and magic happen:
For me none of the above solutions helped. But then I set my web project as startup and then it worked!
We can create a new class file into our solution and add the following code into it then use add-migration it will definitely work
@ajcvickers Hi, thanks the your the link you shared (https://docs.microsoft.com/en-us/aspnet/core/migration/1x-to-2x/). But this article does not give a single example of implementing IDesignTimeDbContectFactory<>
Can we get a convention that behaves similarly, but doesn’t require anything ASP.Net Core specific? I’m writing CLI tools here with no web interface, I don’t want to have to implement an
IDesignTimeDbContextFactorywhen I’m usingAddDbContexton aServiceCollectionanyway…Thank you so much, just change the name of CreateWebHostBuilder solved the problem
Seems this particular issue has a couple of a root causes and we STILL aren’t there yet in working it all out. I will provide another GOTCHA:
If the db doesn’t exist, and you try to
dotnet ef migrations add InitialCreate, it’ll fail. You must run adotnet ef database updatefirst. Got to love those completely misleading error messages.For the record:
I had the same issue which was driving me crazy. I finally found the root cause (in my case)
my appsettings.json had this setting:
"Logging": { "IncludeScopes": false, "LogLevel": { "Default": "Verbose", "System": "Information", "Microsoft": "Information" } }Simply changing it by this solved the problem:
"Logging": { "IncludeScopes": false, "LogLevel": { "Default": "Warning" } }I had scrapped a database, deleted my migrations and tried to start over and started getting this error message.
All I did to get Add-Migration to work again was comment out the seeding method call in Configure() myContext.EnsureSeedDataForContext();
Yes it does actually.
I was able to create the DesignTimeContextFactory. Then I used
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="2.0.1" />instead of<DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="2.0.1" />which allowed me to run migrations where the project wasnetstandard2.0instead ofnetcoreapp2.0. Thanks.@crasshacker you do not need to add IDesignTimeDbContextFactory, in your Program.cs you have to have a method named “BuildWebHost”:
@cbmek you are correct! wow and here I wasted so much time implementing IDesignTimeDbContextFactory and I was so bothered that I had to load appsettings again and none of the articles online even gave a thought about environment specific appsettings and all I need was a method named BuildWebHost
This message may surface if you have an error anywhere in your startup process even if everything else is configured correctly. For me, in Startup.cs I was trying to parse a key which didn’t exist in appsettings.json. I forgot that I had renamed it and never tried running the application which probably would have shown me the exception.
In case this helps anyone. I was getting the “Add an implementation of ‘IDesignTimeDbContextFactory<MyDbContext>’” error too. For me it was because I was not adding the DBContext to my service provider. In my case I happened to be changing from using a SQL Server database to a SQLite one. I had accidentally removed the “UseSqlServer” line without adding back a “UseSqlite”. So now I have something like this in “Startup.cs”
In case this helps anyone. I had the exact same error while creating a new project with an n-Tier design. At some point I had set my data access layer as the default startup project. I found that migrations worked again once I set the startup project to the web project where startup.cs and project.cs resides.
@colotiline It looks like this is fixed in the latest codebase.