Unable to use dotnet ef command in cli - entity-framework

I'm using ASP.NET Core 2.2 in a MVC web applicattion. I can use add-migration and update-database in my PMC and they work fine. BUT when I use their CLI commands in Windows Power Shell like dotnet ef migrations add InitMig they don't work and give this error:
The application to execute does not exist
To make it clear, I adressed the exact project. So there is no problem about directions. but still dotnet ef commands don't work.
I read this Microsoft article and it says I don't need to add any package in my project for NET Core 2.2 apps, to CLI commands work.
Microsoft article
But I added that package to my project to test if dotnet ef works, like this:
<ItemGroup>
<DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="2.0.3" />
</ItemGroup>
so dotnet ef command works and gave its version and the unicorn. Now the problem is I can't use any commands even dotnet ef migrations list the error I get in CLI is:
Unable to create an object of type 'MainDbContext'. For the different
patterns supported at design time,
any dotnet ef command in CLI reuslts in this error. As I mentioned before these commands work fine in PMC.
If u need any part of my project just let me know. I'll share it here.

Check that you are running ef in the correct version of the sdk.
dotnet --version
You can specify the version by creating a global.json file in the root of your project.
{
"sdk": {
"version": "2.2.301"
}
}

Related

How can I call Add-Migration without parameters

I have .net Core 3.1 solution with WebApi and Persistance projects. WebApi is the solution's startup project, Persistance is where DbContext is defined. After a lot of reading and trying stuff, I still cannot achieve the following:
WebApi stays as the solution's startup project.
Migrations folder with all the migrations classes is in the Persistance project.
Migrations can be generated from VS Package Manager Console by typing Add-Migration <migration_name> without any additional parameters like -Project or -StartupProject.
No need to change selection in the Package Manager Console Default project dropdown.
I wanted to achieve the same result but on MAC OS. Because Visual Studio on Mac is not like Window's, We use CLI commands. In my case I had Migration Classes in another project and startup was Api project just like you so i added this to my terminal :
alias migrationfortest='dotnet ef migrations add $1 --project /Users/user/Projects/test-web/Test.Infrastructure'
and you can call this simply by typing migrationfortest "YOURMIGRATIONNAME"
NOTE : For CLI command tools you should add This

Rider. EF Code First Migrations

Is there an easy way to scaffold migrations using old EF outside of Visual Studio? I would like to do it via Rider IDE if it possible.
I don't see these options related to ef core. The plugin makes sense.
(For MacOS, be sure, your dotnet root folder path is /usr/local/share/dotnet/. I'm telling this because Rider installs and places it in another folder. Further it gives rise ef to not work properly. You can see your dotnet folder on terminal by writing which dotnet)
Installing that plugin,
Then,
You can also use a jetbrains plugin made for handling migrations
https://plugins.jetbrains.com/plugin/17026
For EF Core, you can use https://blog.jetbrains.com/dotnet/2017/08/09/running-entity-framework-core-commands-rider/
For EF 6 you may want to check https://blog.jetbrains.com/dotnet/2018/04/06/entity-framework-support-rider-2018-1/
The Package Manager Console tools such as Add-Migration, Scaffold-DbContext commands are PowerShell-based, and the Package Manager Console ties to several Visual Studio-specific objects making it impossible to host it elsewhere - in your case Rider.
In Rider's terminal or anywhere outside of Visual Studio, you can use CLI tools. Equivalents to the highlighted commands would be respectively:
Add-Migration => dotnet ef migrations add MigrationName
Scaffold-DbContext => dotnet ef dbcontext scaffold
You can get more details on JetBrains blog: Running EF Core commands in Rider

UseMySQL extension method not recognized in ASP.NET core

Environment: Ubuntu 16.04, .NET Core 1.10 (1.0.0-preview2-1-003177), Visual Studio Code 1.8.1
I have created an ASP.NET MVC Core application by running the following command:
$ dotnet new -t web
I am able to load the folder in VSC and debug it.
By default, the engine generates code for Sqlite. I am changing it to use MySQL. My changes are based on the information from the following two articles:
http://insidemysql.com/howto-starting-with-mysql-ef-core-provider-and-connectornet-7-0-4/
https://damienbod.com/2016/08/26/asp-net-core-1-0-with-mysql-and-entity-framework-core/
First, I added the following lines into dependencies section of project.json.
"MySql.Data.Core" :"7.0.4-ir-191",
"MySql.Data.EntityFrameworkCore": "7.0.6-IR31"
After running dotnet restore, the required DLLs were downloaded.
The next step was to modify Startup.cs and modify
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlite(Configuration.GetConnectionString("DefaultConnection")));
to
services.AddDbContext<ApplicationDbContext>(options =>
options.UseMySQL(Configuration.GetConnectionString("DefaultConnection")));
Essentially, I am replacing UseSqlite by UseMySQL.
However, extension method UseMySQL or UseMySQL do not seem to be available on DbContextOptionsBuilder.
Wondering if I missed some step somewhere. Regards.
Add the using MySql.Data.EntityFrameworkCore.Extensions; statement.
I've successfully used this in my Mac with the latest version of VS Community in to an ASP CORE MVC project and I just needed to add the following NuGet-Packages:
Microsoft.EntityFrameworkCore
MySql.Data.EntityFrameworkCore
Then using them on your class like:
using Microsoft.EntityFrameworkCore;
using MySQL.Data.EntityFrameworkCore.Extensions;
Notice the MySQL on the USING statement is CAPITAL letter, and it is MySql on the NuGet Package name.
Hope this hel
I also had the same issue even though was installing the Pomelo.EntityFrameworkCore.MySql,
just installed the package through the terminal:
dotnet add package Pomelo.EntityFrameworkCore.MySql
it worked!

The term 'scaffold-dbcontext' is not recognized as the name of a cmdlet, function, script file, or operable program

When trying to scaffold with asp.net core this command
scaffold-dbcontext "Data Source=(local);Initial
Catalog=MyDb;Integrated Security=True;"
Microsoft.EntityFrameworkCore.sqlserver -outputdir Models
Gives this error.
scaffold-dbcontext : The term 'scaffold-dbcontext' is not recognized
as the name of a cmdlet, function, script file, or operable program.
Check the spelling of the name, or if a path was included, verify
that the path is correct and try again. At line:1 char:1
+ scaffold-dbcontext "Data Source=(local);Initial Catalog=MyDB;In ...
+ ~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (scaffold-dbcontext:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
I have tried the solution here, but it does not work for me.
Any idea what the cause/cure could be?
For me apparently it worked once I have also ran in Package Manager console :
Install-Package Microsoft.EntityFrameworkCore.Tools
Also make sure :
To have other dependencies (for example Microsoft.EntityFrameworkCore, Microsoft.EntityFrameworkCore.SqlServer, Microsoft.EntityFrameworkCore.SqlServer.Design...) referenced depending of your needs.
To select the right assembly as target for your commands in the top-right corner of the PM console (I am frequently fooled by forgetting it...)
Another problem I encountered : with the dbcontext located in a separate class library, I was encountering the following error :
Unable to find provider assembly with name
Microsoft.EntityFrameworkCore.SqlServer. Ensure the specified name is
correct and is referenced by the project.
Which I was able to fix by setting my class library as Startup project in VS (don't ask why as it seems meaningless, but it worked).
Late edit, there's something else to know : You can't run Scaffold-DbContext against a class library targetting only .Net Standard, you must also enable netcoreapp in it, or Scaffold-DbContext will complain.
To support both targets, edit the csproj to put : <TargetFrameworks>netcoreapp2.2;netstandard2.0</TargetFrameworks>
Instead of <TargetFramework> section.
After all these you'll be able to run your Scaffold-DbContext command line with proper arguments and connection string.
-- 2022 update --
I'm glad to see that post is still helpful as it receives some new upvotes, but instead of command-line scaffolding, there's a newer solution for the happy users of VS : you can rely on the retro-engineering feature of the extension EF Core Power tools.
I'm using it in all my new projects since a while and I find it much more powerful than raw command line, and it allows you to save your execution settings (which will avoid you to create a .bat with your custom command line).
Of course, it's your choice.
Had the same problem. In my case i was missing some dependencies, so make sure that you have the following one :
Microsoft.EntityFrameworkCore
Microsoft.EntityFrameworkCore.SqlServer
Microsoft.EntityFrameworkCore.Tools
Hope this would help. :)
Make sure that this is available in your project.json file "Microsoft.EntityFrameworkCore.Tools.DotNet": "1.0.0-preview3-final".
Run the command in the package manager console
that's all it will work
Make sure you run VS as Administrator and have installed the following packages:
Microsoft.EntityFrameworkCore.SqlServer
Microsoft.EntityFrameworkCore.SqlServer.Design
Microsoft.EntityFrameworkCore.Tools
Scaffold command is part of dbcontext command in EF. Below are the details for successful scaffold:
Package references required:
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="3.0.0"/>
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="3.0.0"/>
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.0.0"/>
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="3.0.0"/>
So our scaffold command should look like:
dotnet ef dbcontext scaffold "Server=localhost\SQLEXPRESS;Database=MyDatabase;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -o OutputDirectory
Your Server value might differ as per your Db server name. Replace MyDatabase with your Database name like master and OutputDirectory to the location you want your newly created scaffolded classes like Models folder.
Make sure you are using the right console, the "Package Manager Console". There is also a "Terminal" console which looks very similar, but doesn't work for this command. Package Manager Console can be found in View -> Other Windows (as of Visual Studio 2019, ver. 16.6.5)
I had installed Microsoft.EntityFrameworkCore.Tools from NuGet Package Manager and it was visible in the installed packages. But I kept getting this error.
Restarting Visual Studio (2019/Version 16.4.4) fixed it for me.
With VS2022, none of them worked.
But I installed EF
dotnet tool install --global dotnet-ef
and changed the code;
dotnet ef dbcontext scaffold "Server=servername;Database=dbname;Persist Security Info=True;User ID=XXX;Password=YYY;" Microsoft.EntityFrameworkCore.SqlServer -o Models
Also I had to install .Net 6.0 hosting bundle
https://dotnet.microsoft.com/en-us/download/dotnet/6.0/runtime?cid=getdotnetcore
For me this error was caused by extra spacing was added around the hyphens, which was for some reason added when copy pasting from the command from the docs. Removing the spacing fixed it.
causes error:
Scaffold - DbContext "Server=(localdb)\mssqllocaldb;Database=myDbName;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer - OutputDir Models
the fix:
Scaffold-DbContext "Server=(localdb)\mssqllocaldb;Database=myDbName;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models
The docs also say if you receive this error, try restarting Visual Studio.
https://learn.microsoft.com/en-us/ef/core/get-started/aspnetcore/existing-db
If you're using .NetCore 2.2 then the command below works like a charm for me either in Command Prompt (CMD) or on Git Bash.
Make sure that you are directly on the project folder before running the command.
For example C:\App\ProjectName:
dotnet ef dbcontext scaffold "Server=.\;Database=Databasename;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -o Model
I ran into another cause of this error recently: NuGet itself was out of date.
Updating NuGet resolved the issue.
If Devanathan's answer doesn't work for you, check to make sure NuGet itself is up to date.
If your solution has more than one project and the EF files are not in the startup project, make sure you choose the correct project here

How to execute EntityFramework CLI commands programmatically in .NET Core?

How to run those dotnet.exe ef <command> commands programmatically in .NET Core?
For example to add migration I'm running in terminal dotnet ef migrations add NewMigration and it will indeed create Migrations folder with migration classes, but to create new Migration (for example) programmatically from C# code?
Don't suggest Process.Start("cmd bla-bla") since code should be cross-platform and that dotnet ef runs some code from some EntityFrameworkCore package anyway. Question is what code?
EF Core API isn't really designed for the scenario, but if you want to do this anyways, you'll need to repeat the logic that "dotnet-ef.dll" does to gather project context and compilation output, and then instantiate and use MigrationsOperations manually.
See https://github.com/aspnet/EntityFramework/blob/1.0.0/src/Microsoft.EntityFrameworkCore.Design.Core/Design/MigrationsOperations.cs and https://github.com/aspnet/EntityFramework/blob/1.0.0/src/Microsoft.EntityFrameworkCore.Design/Internal/OperationExecutor.cs
Use caution: these are "Internal" APIs, which means their usage may break from version to version. "dotnet ef" is going to change a great deal between the current release (1.0.0-preview2) and the next release. (For example, the entire tooling implementation will change. See https://github.com/aspnet/EntityFramework/issues/5334).