I'm building a new project using ASP.net Core 2 and EntityFrameWorkCore 2.1.0 and I began to build the database structure. Now I have to make my first Migration to get my database ready and when I execute 'Add-Migration Init' into the Package Manager Console I got this error:
The current CSharpHelper cannot scaffold literals of type 'Microsoft.EntityFrameworkCore.Metadata.Internal.DirectConstructorBinding'. Configure your services to use one that can.
Also I tried this documentation https://learn.microsoft.com/en-us/aspnet/core/data/ef-mvc/migrations and the message I got is:
Unable to create an object of type 'ApplicationDbContext'. Add an implementation of 'IDesignTimeDbContextFactory<ApplicationDbContext>' to the project, or see https://go.microsoft.com/fwlink/?linkid=851728 for additional patterns supported at design time.
I also followed this article without any success.
If I try without Microsoft.AspNetCore.Identity.EntityFrameworkCore 2.0.2 and with a simple 2 tables structure I'm able to make it work.
So now I need your help...
Make sure that you have the required NuGet packages installed:
Microsoft.EntityFrameworkCore.SqlServer
Microsoft.EntityFrameworkCore.Design
I found some reasons why we can get hard time to use migration with the latest version of ASP.net Core 2 at this time.
First of all, if you just migrate from an old project which is not built from ASP.net Core at all, you will have to add a Context Factory to make Migrations work. Here my own Context Factory:
public class ApplicationDbContextFactory : IDesignTimeDbContextFactory<ApplicationDbContext>
{
public ApplicationDbContext CreateDbContext(string[] args)
{
var builder = new DbContextOptionsBuilder<ApplicationDbContext>();
builder.UseSqlServer("Server=(local)\\SQLEXPRESS;Database=yourdatabase;User ID=user;Password=password;TrustServerCertificate=True;Trusted_Connection=False;Connection Timeout=30;Integrated Security=False;Persist Security Info=False;Encrypt=True;MultipleActiveResultSets=True;",
optionsBuilder => optionsBuilder.MigrationsAssembly(typeof(ApplicationDbContext).GetTypeInfo().Assembly.GetName().Name));
return new ApplicationDbContext(builder.Options);
}
}
If you divided your project into layers for architecture purpose, add the Context Factory inside the Repository Layer or in the same library where your DbContext is.
Secondly, before any attempt to add a migration, you must set the selection of “set as startup project” on the repository library or where your DbContext is.
Then, those are the packages you need to use for migration:
Microsoft.AspNetCore.Identity.EntityFrameworkCore
Microsoft.EntityFrameworkCore.Design
Microsoft.EntityFrameworkCore.SqlServer
That’s all!
Be careful when you add other packages because they can break the Migration system. As an example, if you use a Unit of Work & Repositories Framework like URF and install URF.Core.EF.Trackable -Version 1.0.0-rc2, you will no longer be able to add migration. Instead use URF.Core.EF.Trackable -Version 1.0.0-rc1. I guess this can happen with many other packages as well.
Finally, read this article will be helpful. It’s a little outdate but it can help people out there.
Cheers
How do you arrange the main method in "Program.cs"?
This error can be amenable to a old initialization pattern.
From the Asp Net migrations guidelines:
The adoption of this new 2.0 pattern is highly recommended and is
required for product features like Entity Framework (EF) Core
Migrations to work. For example, running Update-Database from the
Package Manager Console window or dotnet ef database update from the
command line (on projects converted to ASP.NET Core 2.0) generates the
following error:
Unable to create an object of type ''. Add an implementation of 'IDesignTimeDbContextFactory' to the
project, or see https://go.microsoft.com/fwlink/?linkid=851728 for
additional patterns supported at design time.
Check at this link of the correct implementation
In my case, the dbcontext was different in Startup within ApplicationDbContext class.
services.AddDbContext<DbContext>
to
services.AddDbContext<ApplicationDbContext>
I have 4 projects :
Toombu.Entities : all models are there
Toombu.DataAccess: Mapping, Repository and ToombuContext
Toombu.Logique : Logic of my application
Toombu.Web : MVC 4 application. With all others DLL.
I tried to enable migration in Toombu.Web but i had this error :
No context type was found in the assembly
How can I enable migration ?
I am surprised that no one mentioned the obvious answer to this question: Entity Framework requires a context before enable-migrations will work. The error message the OP posted suggests that no context was found. Sure, it could be because the package manager console doesn't "see" the context--in which case the accepted answer is a possible solution (another solution is one I suggest, below). But a context must exist in the current project (assembly) before any other solutions will work.
What does it mean to have a context? It means that there must exist a class in your project that inherits from DbContext (in System.Data.Entity). Here is an example:
public class MyDbContext : DbContext
{
public MyDbContext()
{
}
}
Be sure you use
using System.Data.Entity;
before the code above has access to the DbContext class and that you have used NuGet to get Entity Framework 4.1 or later for the current project.
If all along you had a context but the Package Manager Console just doesn't "see" it: In Visual Studio 2013 you don't have to use the -ProjectName switch. Instead, go to the Package Manager Console (it's available in the View | Other Windows list), and look at the two dropdowns that appear at the top of the Package Manager Console dockable window. The first dropdown is for Package Source; the second is for Default Project. If you dropdown the Default Project and select a project in your solution then whatever commands you issue in the Package Manager console will be executed against the selected project.
use -ProjectName option in Package Manager Console:
Enable-Migrations -ProjectName Toombu.DataAccess -StartUpProjectName Toombu.Web -Verbose
Change the default project and choose the startup project from dropdown:
In my case, the NuGet package "Microsoft.EntityFrameworkCore.Tools" was missing
If anyone is still facing this problem. I solved it by using the following command:
Enable-Migrations -ProjectName <YOUR_PROJECT_NAME> -ContextTypeName <YOUR_CONTEXT_NAME>
Don't forget to use the full path to your context name.
You dbcontext is in Toombu.DataAccess So you should enable migrations in Toombu.DataAccess.
I created a Class in the Models directory called: myData with the following code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
namespace Vidly.Models
{
public class MyDbContext : DbContext
{
public MyDbContext()
{
}
}
}
rebuilt the app with: control-shift-b
then ran the following in the nuGet Console:
Enable-Migrations -StartUpProjectName Vidly -ContextTypeName Vidly.Models.MyDbContext -Verbose
the Console returned:
Using StartUp project 'Vidly'.
Using NuGet project 'Vidly'.
Checking if the context targets an existing database...
Code First Migrations enabled for project Vidly.
Enable-Migrations -StartUpProjectName Vidly -ContextTypeName Vidly.Models.myData -Verbose
And the FrameWork created a Migrations directory and wrote a Configuration.cs template in there with the following code:
namespace Vidly.Migrations
{
using System;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
internal sealed class Configuration : DbMigrationsConfiguration<Vidly.Models.MyDbContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
}
protected override void Seed(Vidly.Models.MyDbContext context)
{
// This method will be called after migrating to the latest version.
// You can use the DbSet<T>.AddOrUpdate() helper extension method
// to avoid creating duplicate seed data.
}
}
}
Follow the below steps to resolve the issue
Install-Package EntityFramework-IncludePrerelease
or Install entity framework from Nuget Package Manager
Restart visual studio
After that I was getting "No context type was found in assembly"
To resolve it - This "No context" that mean you need to create class in "Model" folder in your app with suffix like DbContext ... like this AppDbContext. There you need to include some library using System.Data.Entity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
namespace Oceans.Models
{
public class MyDbContext:DbContext
{
public MyDbContext()
{
}
}
}
After that run the below command on Package Manager:
Enable-Migrations -ProjectName <YourProjectName> -ContextTypeName <YourContextName>
My Project Name is - MyFirstApp and AppDbContext is inside the Model Folder so path is like
Enable-Migrations -StartUpProjectName MyFirstApp -ContextTypeName MyFirstApp.Models.AppDbContext
In mosh tutorial, individual user account was selected which created a db context in the template.
Also, make sure EntityFramework is installed in the Nuget package manager.
If you use Both Entity Framework 6 and Entity Framework Core are installed. The Entity Framework 6 tools are running.
Use EntityFrameworkCore\Enable-Migrations for Entity Framework Core. same as for add migration and update database.
Thanks for the suggestions, I solved the problem by combining all the solutions here. At first I created the DbContext Model:
public class MyDbContext: DbContext
{
public MyDbContext()
{
}
}
After creating the dbcontext class, I ran the enable-migration command with the project Name: enable-migrations -ProjectName YourProjectName
I had to do a combination of two of the above comments.
Both Setting the Default Project within the Package Manager Console, and also Abhinandan comments of adding the -ContextTypeName variable to my full command. So my command was as follows..
Enable-Migrations -StartUpProjectName RapidDeploy -ContextTypeName RapidDeploy.Models.BloggingContext -Verbose
My Settings::
ProjectName - RapidDeploy
BloggingContext (Class Containing DbContext, file is within Models folder of Main Project)
My problem was link---->
problem1
I solved that problem with one simple command line
Install-Package EntityFramework-IncludePrerelease
After that, i needed to face with one more problem, something like:
"No context type was found in assembly"
I solve this really easy. This "No context" that mean you need to create class in "Model" folder in your app with suffix like DbContext ... like this MyDbContext.
There you need to include some library using System.Data.Entity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
namespace Oceans.Models
{
public class MyDbContext:DbContext
{
public MyDbContext()
{
}
}
}
After that,i just needed this command line:
Enable-Migrations -ProjectName <YourProjectName> -ContextTypeName <YourContextName>
I got this problem first:
PM> add-migration first
No migrations configuration type was found in the assembly 'MyProjectName'. (In Visual Studio you can use the Enable-Migrations command from Package Manager Console to add a migrations configuration).
then i tried this:
PM> Enable-Migrations
No context type was found in the assembly 'MyProjectName'.
Then the right command for me :
PM> Enable-Migrations -ProjectName MyProjectName -ContextTypeName MyProjectName.Data.Context
After that i got this error message even though Context inherits from DbContext
The type 'Context' does not inherit from DbContext. The DbMigrationsConfiguration.ContextType property must be set to a type that inherits from DbContext.
Then i Installed
Microsoft.EntityFrameworkCore.Tools
ITS OK NOW but the message is funny. i already tried add migrations at first :D
Both Entity Framework Core and Entity Framework 6 are installed. The Entity Framework Core tools are running. Use 'EntityFramework6\Enable-Migrations' for Entity Framework 6.
Enable-Migrations is obsolete. Use Add-Migration to start using Migrations.
Change the default project to data access
change the default project dropdown in the package manager console to data access and give enable migrations...
Thats all success
Using the Package Manager, you need to re-install Entity Framework:
Uninstall-Package EntityFramework -Force
Then install it for each project:
Install-Package EntityFramework
Then do not forget to restart the studio.
Ensure you are using the same version of Entity Framework across all projects using the NuGet Package Manager.
Recent windows updates may have installed a newer version of Entity Framework into your active project.
Background:
Around 16 Mar 2016, I started getting this error when trying to add migrations to a project where I had already enabled migrations and had successfully done migrations for.
I noticed that around March 10, a new stable version of Entity Framework 6 had been released.
If I specified the -ContextTypeName parameter in the enable-migrations command, I got an error indicating the migrations were already enabled.
Resolution:
1) Tools -> Nuget Package Manager -> Manage Nuget Packages for Solution
2) (Not sure if this step is necessary, but..) I updated my version of the Nuget Package Manager to the latest version. Also, after updating my version of Nuget Package Manager, I had to restart Visual Studio twice before the NuGet Command line would work properly.
3) Tools -> Nuget package Manager -> Manage Nuget Packages for Solution -> Search Installed packages -> Type Entity Framework
a. You may see more than one version of Entity Framework there.
b. Click Manage on each version of Entity Framework and ensure that your projects are using the SAME version of Entity Framework.
Uncheck the version of Entity Framework that you are not using and for the version of Entity Framework you ARE using make sure it is checked across your projects that need it.
Again, as noted in step 2, I had to restart visual studio twice to get the NuGet Package Manager Console to work properly after updating my version of the NuGet Package Manager. I got an error starting the console the first time, and
"exception calling createinstancefrom with 8 arguments could not load file or assembly EntityFramework" when running the enable-migrations command the second time.
Restarting visual studio seemed to resolve those issues, however.
This error getting because of the compiler not getting 'Context' class in your application. So, you can add it manually by Add --> Class and inherit it with 'DbContext' Class
For Example :
public class MyDbContext : DbContext
{
public DbSet<Customer> Customer { get; set; }
public MyDbContext()
{
}
}
I have been getting this same problem. I have even tried above enable migrations even though I have already done. But it keeps giving same error. Then I had to use the force switch to get overcome this problem. I am sure this will help in someone else's case as well as its a possible work around.
After enabling migration with force, you should update your database (Make sure default project is set correctly). Otherwise you will get another problem like explicit migrations are pending.
Then just execute your add-migrations or any other commands, it should work.
Enable-Migrations -ProjectName <PROJECT_NAME> -ContextTypeName <FULL_CONTEXT_NAMESPACE.YOUR_CONTEXT_NAME> -force
Adding a class which inherits DbContext resolved my problem:
public class MyDbContext : DbContext { public MyDbContext() { } }
How to Update table and column in mvc using entity framework code first approach
1: tool > package manager console
2: select current project where context class exist
3: Enable migration using following command
PM > enable-migrations
4: Add migration folder name using following command
PM > add-migration MyMigrationName
4: Now update database following command
PM > update-database
enable-migrations -EnableAutomaticMigration:$false with this command you can enable migration at Ef 6.3 version because C# enable as default migrations at Ef 6.3 version.
I have encountered this problem a few times and in my case I uninstalled EntityFramework nuget package and installed EntityFrameworkCore nuget package, entityFramework.design and entityframework.tools
I got the same error when I had Authentication disabled/chose "No Authentication'. I re-made my project and chose "Individual User Accounts" and I didn't get the error anymore.
When I faced the same problem, I found that I had renamed my project in the solution explorer.
I needed to open the project in notepad and change the old name to new name.
OPs question was for EF5; I had the same problem with EF6, and my experience was quite similar. Multiple answers here reference EntityFrameworkCore, but using that was a huge misdirect for me.
It seems many things can cause the OPs error; I think both jazimov and Sadjad Khazaie presented good solutions that are useful for both EF and EFCore. However, when I had EFCore installed alongside EF6, that actually CAUSED this problem. It seems that my existing EF6 codebase was using EF6 migrations, and with EntityFrameworkCore packages installed, I got the No context type was found in the assembly error because the EFCore add-migration command was running.
When I removed the EntityFrameworkCore packages, the problem went away.
Note: sometimes I got a warning that both EntityFrameworkCore and EntityFramework were installed when I ran add-migration, but not always. One way to be sure: try enable-migrations, which is available with EntityFramework but is not available (or necessary) with EntityFrameworkCore.
Create a File called MyDBContext inside Models Folder
using System.Data.Entity;
namespace VSR.Models
{
public class MyDbContext: DbContext
{
public MyDbContext()
{
}
}
}
Now Try to execute Enable-migrations. It will work.
namespace EntityFrameworkCodeFirst.Module
{
public class MyDbContext: DbContext
{
public MyDbContext()
{
}
}
}
And if you have Multiple project in one solution than you have to use below commands:-
Enable-Migrations -ProjectName EntityFrameworkCodeFirst
Worked for me:
UnInstall-Package EntityFramework
Restart Visual Studio
Install-Package EntityFramework
Build project
I just got on board with EF 5 and am using their code-first migrations tool but I seem to get an error when I try to enable migrations.
I type Enable-Migrations into the package manager console and then it says
No classes deriving from DbContext found in the current project.
Edit the generated Configuration class to specify the context to enable migrations for.
Code First Migrations enabled for project MyApp.MvcUI.
It then creates a Migrations folder and a Configuration class in my MvcUI project. Thing is, my DbContext lives in a class library project called MyApp.Domain. It should be doing all that in that project and should have no problem finding my DbContext.
Oh wow, nevermind. I'm dumb.
In the Nuget package manager console there is a dropdown menu at the top labeled "Default Project:". Make sure you set that to the project you want to run the command against.
Hopefully this helps someone else avoid my embarrassing mistake.
There are actually 3 ways to make Nuget commands run in a specific project:
[Package Manager Console] Set the active project in the dropdown at the top of the console toolwindow
[Package Manager Console] Look for a parameter to specify the project. For some cmdlets I've seen -ProjectName and some use -Project
[Solution Explorer] Right-click the project you want, and use the graphical package manager window (Manage NuGet Packages...).
When I user the Add-Migration command of Entity Framework migration I get the following exception:
System.NullReferenceException: Object reference not set to an instance of an object.
at System.Data.Entity.Migrations.Extensions.ProjectExtensions.GetFileName(Project project, String projectItemName)
at System.Data.Entity.Migrations.MigrationsCommands..ctor(Object project, Object startUpProject, String configurationTypeName, String connectionStringName, String connectionString, String connectionProviderName, PSCmdlet cmdlet)
Any insight?
I've seen this before when there are multiple projects in the solution and the "wrong" project is selected as the startup project. For example, somebody else reported that in an Azure hosted MVC3 website they had the Azure project as the startup project instead of the MVC project. Switching over to the MVC project as the startup fixed the issue.
Update: This has been fixed in EF5-beta2, which is now available on NuGet.
You can actually very easily specify the target project in your Package Manager Console when calling any EF command by just using the correct flags and arguments, for instance, given a project called ProjectFoo out of a solution with multiple projects:
enable-migrations -projectname projectfoo
add-migration "Initial" -projectname projectfoo
update-database -projectname projectfoo
etc...
Easy as pie.