Add-Migration Error in Entity Framework Core - c#

I am following Julie Lerman's Getting Started with Entity Framework Core 2.0 tutorial. I have installed Microsoft.EntityFrameworkCore.SqlServer Version 2.0.2. When I try to run add-migration initial (Package Manager Console) in VS 2017 I am obtaining the below error :
System.IO.FileLoadException: Could not load file or assembly 'Microsoft.EntityFrameworkCore.SqlServer, Version=2.0.2.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)
File name: 'Microsoft.EntityFrameworkCore.SqlServer, Version=2.0.2.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'
When I run dotnet --version i get 2.1.3. Can anybody help me rectify this error.
Screenshot :
Thanks in Advance.

Following the very same Pluralsight video, I ran into this same problem. After running:
PM> install-package Microsoft.EntityFrameworkCore.SqlServer
with the default project set to SomeUI
I was able to get the add-migration initial to run without any problems at all, after doing so.

I know the following is not an exact answer to my own question. But rather than waiting to somebody answer how to solve it in VS 2017 ( Windows ) I am taking a Terminal Approach on my Mac and using dotnet cli to recreate the solution (Julie Lerman hope you won't send your favorite Samurai for a battle :P)
Note: Steps below is for Mac. Windows users having SQl Server Installed can Skip Step 1.
Step 1 : Install Docker and Pull MSSQL Image
a. Install docker and pull latest mssql image for linux using :
sudo docker pull microsoft/mssql-server-linux
b. Start the docker image using :
sudo docker run -e 'ACCEPT_EULA=Y' -e 'SA_PASSWORD=
<ComplexPassword>' -p 1433:1433 -d microsoft/mssql-server-linux
c. Optional. Install sql-cli using npm install -g sql-cli. Now you can connect to Sql Server running on Docker using mssql -s 127.0.0.1 -u sa -p.
Step 2 : Create .sln, .csproj and add references using dotnet cli
Create directory for Project and under it create a .sln file using: dotnet new sln -n SamuraiApp
Create Data and Domain class Library Projects using : dotnet new classlib -n SamuraiApp.Data and dotnet new classlib -n SamuraiApp.Domain
Create and Empty ASP.NET Core Project using dotnet new web -n SamuraiApp.UI
Add Entity Frmaework Core to Data ClassLibrary using : cd SamuraiApp.Data and dotnet add package Microsoft.EntityFrameworkCore.SqlServer
Add Entity Framework Core Design to UI Project Using : cd SamuraiApp.UI/ and dotnet add package Microsoft.EntityFrameworkCore.Design
Run dotnet restore
Step 3: Add References
Execute dotnet add SamuraiApp.Data reference SamuraiApp.Domain/SamuraiApp.Domain.csproj to add Domain as a reference to Data.
Execute dotnet add SamuraiApp.UI reference SamuraiApp.Domain/SamuraiApp.Domain.csproj to add Domain as reference to UI.
Execute dotnet add SamuraiApp.UI reference SamuraiApp.Data/SamuraiApp.Data.csproj to add Data as reference to UI.
Execute below commands to add all three projects to solution:
dotnet sln add SamuraiApp.Data/SamuraiApp.Data.csproj
dotnet sln add SamuraiApp.Domain/SamuraiApp.Domain.csproj
dotnet sln add SamuraiApp.UI/SamuraiApp.UI.csproj
Open SamuraiApp.Data.csproj in your favorite text editor and add the following:
<ItemGroup>
<DotNetCliToolReference
Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="2.0.0" />
</ItemGroup>
To enable dotnet ef.
Step 4 : Write Domain Classes, DataContext class and add migration
cd into SamuraiApp.Data folder and execute the below command to add initial migration:
dotnet ef migrations add Initial --startup-project ../SamuraiApp.UI
Hope it helps to somebody. But still In windows using VS 2017 I am facing issues and would hope somebody will help me solve it.
Thanks :)

Related

Attempting to figure out the EntityFramework metadata for the model and DbContext: 'Employee'

I am trying to generate drivers from the command ..
dotnet aspnet-codegenerator controller -name EmployeeController -m Employee -dc EmsContext --relativeFolderPath Controllers --useDefaultLayout --referenceScriptLibraries
Attempting to figure out the EntityFramework metadata for the model and DbContext: 'Employee'
A file matching the name MvcControllerWithContext.cshtml was not found within any of the folders:
at Microsoft.VisualStudio.Web.CodeGeneration.ActionInvoker.<BuildCommandLine>b__6_0()
at Microsoft.Extensions.CommandLineUtils.CommandLineApplication.Execute(String[] args)
at Microsoft.VisualStudio.Web.CodeGeneration.ActionInvoker.Execute(String[] args)
at Microsoft.VisualStudio.Web.CodeGeneration.CodeGenCommand.Execute(String[] args)
It is the last step according to a documentation, I am starting with this Framework but I cannot get out of this status. I am using Ubuntu and all through the terminal. If someone can give me an indication of how to solve it, I would really appreciate it.
As #ericc-eacs Answer, you need to copy the template and in case you just following the getting started tutorial(.net core), make sure to remove the folder to the template of identity as when you build it will give some errors. You just need the templates to create the views and controllers.
What version of the dotnetcore SDK are you using?
dotnet --version
You may need to install a different version of the aspnet-codegenerator.
Some helpful commands:
dotnet tool uninstall --global dotnet-aspnet-codegenerator
dotnet tool install --global dotnet-aspnet-codegenerator --version 3.1.0
dotnet tool update -g dotnet-aspnet-codegenerator
I have the solution for UBUNTU valid for net core 3.0, 3.1, and 5.0.
27/NOVEMBER/2020
ControllerGenerator contains de file MvcControllerWithContext.cshtml
You just copy the Templates folders Template/ControllerGenerator and Template/ViewGenerator to own project.
Look the version in this example is 5.0.0enter image description here
This is the path of the missing files: /home/$USER/.nuget/packages/microsoft.visualstudio.web.codegenerators.mvc/5.0.0/Templates
I can confirm that this issue exists at least since november and have not found solution for it. Using Ubuntu 18.04.5 LTS, Rider EAP 2020.3. C# 9, dotnet-aspnet-codegenerator version '5.0.1', dotnet 5.0.102.
When running the utility to build crud pages for Razor Pages web app:
dotnet aspnet-codegenerator razorpage -m GpsSession -dc ApplicationDbContext -udl -outDir Pages/GpsSessions --referenceScriptLibraries
The following output is given:
Building project ...
Finding the generator 'razorpage'...
Running the generator 'razorpage'...
Attempting to figure out the EntityFramework metadata for the model and DbContext: 'GpsSession'
A file matching the name Create.cshtml was not found within any of the folders:
at Microsoft.VisualStudio.Web.CodeGeneration.ActionInvoker.<BuildCommandLine>b__6_0()
at Microsoft.Extensions.CommandLineUtils.CommandLineApplication.Execute(String[] args)
at Microsoft.VisualStudio.Web.CodeGeneration.ActionInvoker.Execute(String[] args)
at Microsoft.VisualStudio.Web.CodeGeneration.CodeGenCommand.Execute(String[] args)
When I run the same command on same repository in Win10 then everything works perfectly, crud pages are generated without any errors.

'dotnet ef' command is not working in .NET Core 2.2

I was trying to use Visual Studio Code as the IDE. When I needed to use the 'add-migrations' command,
I came across the situation of using the 'dotnet ef migrations add name' command, but when I try to use this command I get the error:
dotnet : Could not execute because the specified command or file was not found.
At line:1 char:1
+ dotnet ef
+ ~~~~~~~~~
+ CategoryInfo : NotSpecified: (Could not execu... was not found.:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
Possible reasons for this include:
* You misspelled a built-in dotnet command.
* You intended to execute a .NET Core program, but dotnet-ef does not exist.
* You intended to run a global tool, but a dotnet-prefixed executable with this name could not be found on the PATH.
I've tried several solutions and none worked, is there any way out?
I'm using .NET Core 2.2.
UPDATE!
Now that you have the tool working, we can tell the it where to locate the context.
You mention you have separate projects for the API and Data, so let's name them like that:
Let's assume you have this structure:
Root:
├───Api:
| Api.csproj
├───Data:
| Data.csproj
| YourDbContext.cs
The Api and Data projects are separated and you have an EF DbContext called YourDbContext.
This is what you need to do.
Navigate to the Api directory.
> cd Api
> dotnet ef migrations add Initial --project ..\Data\Data.csproj --context YourDbContext
This is what's happening:
We're running the tool from the main Api project and using --project to flag the Data project.
I've also added the --context parameter just in case you have more that one, you know how to point to one of them.
Please, go ahead and try and let me know how this works.
Initial Approach
OK, I ran the command from a project directory using the version 3.0.100 of the dotnet sdk:
See the output:
> dotnet ef
Could not execute because the specified command or file was not found.
Possible reasons for this include:
* You misspelled a built-in dotnet command.
* You intended to execute a .NET Core program, but dotnet-ef does not exist.
* You intended to run a global tool, but a dotnet-prefixed executable with this name could not be found on the PATH.
This is exactly the same output you're getting, so my guess is that you think you're using version 2.2 but maybe you're not.
You need to run that command from above from your solution/project directory, and verify the SDK is not a 3.x.
You can also "force" the sdk to be 2.2.402 for example if you create a global.json file in the project root with the the below content:
{
"sdk": {
"version": "2.2.402"
}
}
This way, regardless of the SDK you have installed in your system, dotnet will use the version 2.2.402 (or the one you set in the file).

Unable to retrieve project metadata. Ensure it's an MSBuild-based .NET Core project. (Migrations)

I have a project with this structure
TooSeeWeb.Infrastructure is for migrations.
When I try to run migrations with this command
dotnet ef migrations add ExampleMigration -s ..\TooSeeWeb
I have this error
Unable to retrieve project metadata. Ensure it's an MSBuild-based .NET Core project. If you're using custom BaseIntermediateOutputPath or MSBuildProjectExtensionsPath values, Use the --msbuildprojectextensionspath option
How I can fix this?
This is 2 years old but I was just in the same situation so it is still relevant. It's first result on Google for this error.
So I can see in your Screenshot that you are not in the standard Windows Visual Studio so I assume you are not on Windows (makes a difference in how to write file paths). Also I can see that you used ..\TooSeeWeb with a backslash.
Solution: Change all \ to a / forward slash so in your case I guess it would be:
dotnet ef migrations add ExampleMigration -s ../TooSeeWeb
For me it was working on Windows but failing on macOS (OS X) with this error:
Unable to retrieve project metadata. Ensure it's an SDK-style project.
If you're using a custom BaseIntermediateOutputPath or
MSBuildProjectExtensionsPath values, Use the
--msbuildprojectextensionspath option.
Additionally it gives the information (that gives a better hint):
MSBUILD : error MSB1009: Project file does not exist.
Here my more complex statement WORKING with forward slashes:
dotnet ef --startup-project ./MainProject.csproj migrations add MyMigration --context MyDbContextPostgreSQL --output-dir Migrations --project ../MyDatabasePostgreSQL/MyDatabasePostgreSQL.csproj
You have to point to your web project
dotnet ef --startup-project ../TooSeeWeb migrations add MigrationName -c NameOfYourDBContext
More details about multi project you can find https://learn.microsoft.com/en-us/ef/core/managing-schemas/migrations/projects
I had the same error. I solved it by including the nuget package:
Microsoft.EntityFrameworkCore.Tools
just add the path to your startup project and database project like this:
dotnet ef database update --verbose --project "src/Services/Discount/Discount.Infrastructure.Rdms" --startup-project "src/Services/Discount/Discount.Web"
The path should be relative to your current directory to the destination directory, for instance, if I change my current directory to /src the path would be Services/Discount/Discount.Infrastructure.Rdms
The problem for me was that the project was in the solution folder so I had to specify the project path like this
dotnet ef migrations add InitialCreate --project SolutionName/ProjectName.csproj
My error was similar, but different. In fact the same error as #CodingYourLife mentions (perhaps the error wording has changed over time, or it is in fact a different error), anyway... This was the error:
Unable to retrieve project metadata. Ensure it's an SDK-style project. If you're using a custom BaseIntermediateOutputPath or MSBuildProjectExtensionsPath values, Use the --msbuildprojectextensionspath option.
It turned out that I needed to run the dotnet ef dbcontext scaffold <list_of_options> command from the parent folder (the one with the solution file in it - not from the PROJECT folder). I used cd .. (to move up one folder) and re-ran the command, and it created my database-context and EF classes for the tables specified.
I don't know how this problems appeared.
But i truly know that most developers come from using these commands:
dotnet ef migrations add "MigrationName" -s ../ProjectName
dotnet ef migrations remove -s ../ProjectName
dotnet ef database update -s ../ProjectName
So replaced them with these:
dotnet ef --startup-project ../ProjectName migrations add
MigrationName -c DbContextName
dotnet ef --startup-project ../ProjectName database update -c
FoodTownDbContext
I think the same apply for this,but haven't tested it:
dotnet ef --startup-project ../ProjectName migrations remove
-c DbContextName
first of all, your need to see the exact context name. This is needed for
dotnet ef migrations add -c <your context name>
You can see your contexts in your project by using this command:
dotnet ef dbcontext list
You will see something like below👇
AspNetCore.Jwt.Sample.Config.MyIntIdentityContext
AspNetCore.Jwt.Sample.Config.MyIdentityContext
See... there is more than one context. Choose&copy your context's full name and paste it after -c option
dotnet ef migrations add Initial -c AspNetCore.Jwt.Sample.Config.MyIntIdentityContext
use as above☝.
and that is ok! It works well now.
possible reasons:
main reason is your project includes more than one context class
in my case. Context class was in a file with other classes.(i.e.) this config (.cs)file from this impressive github repository
usually I have this problem when I receive updates for dotnet sdks. ProgramFiles/dotnet/sdk.
The problem is that I use an MSBuildSDKsPath system variable and this path doesn't update after dotnet sdk updates.
If you face the same problem, and use the same system variable, that can be the solution.
I am using Entity Framework Core .NET Command-line Tools 6.0.10, and the following worked for me.
Make sure you install the EF tooling globally
dotnet tool install dotnet-ef --global
Make sure you update it to the latest
dotnet tool update dotnet-ef --global
Open a Powershell off your start up project. In your case, it would be TooSeeWeb? Your Powershell should default the root to something like
PS C:\your-user\source\repos\TooSeeWeb\src\TooSeeWeb>
Run the following command to add a migration
dotnet ef migrations add ExampleMigration
-c YourDbContext
-p ../TooSeeWeb.Infrastructure
-o Data/Migrations
-p should set the project where you want the migrations to be put in.
-o is the directory you want to put files in, and it's relative to the project directory you just set with -p.
You can also use -s to set the start up project, where you have your connection string. But since I open the Powershell off the start up, I don't have to specify this, as it defaults to the current working directory.
You can do dotnet ef migrations add -h to see the whole list of optional arguments and what they do.
In my case it was caused by EF versions that I had installed.
I had Entity Framework Core .NET Command-line Tools 7.0.1 installed and the project I was trying to add the migration to, was using EF 6.
Solution was to run EntityFramework6\Add-Migration instead of Add-Migration

How to fix NU1212 for dotnet tool install

I am building a dotnet core tool and I am having trouble installing it globally. I can replicate the problem I am having but don't know how to fix it. Below are my steps
dotnet new console -o testconsole
Modify testconsole.csproj to include <PackAsTool> and <PackageOutputPath>
testconsole.csproj
dotnet restore testconsole.csproj
dotnet build testconsole.csproj
dotnet pack testconsole.csproj
dotnet tool install -g -v d --add-source ./nupkg testconsole
When installing I receive the below error
error NU1212: Invalid project-package combination for TestConsole 1.0.9. DotnetToolReference project style can only contain references of the DotnetTool type
install error
Here is a copy of testconsole.nuspec from the nupkg that includes
<packageType name="DotnetTool" /> per the suggestion from https://natemcmaster.com/blog/2018/05/12/dotnet-global-tools/
testconsole.nupsec
After finding the root cause, this error is hilarious, but also an indication of systematic issue.
Do you see this part of the warning in your output?
Package 'TestConsole 1.0.9' was restored using '.NETFramework,Version=v4.6.1' instead of the project target framework '.NETCoreApp,Version=v2.1'. This package may not be fully compatible with your project
What is this version 1.0.9? Where is .NET Framework 4.6.1 coming from? There's nothing like that in the .NET Core SDK (I looked through the sources) or under the testconsole directory on my disk.
Lets reduce the logging verbosity and re-run out install command:
$ dotnet tool install -g -v n --add-source ./nupkg testconsole
Build started 2018-09-26 7:16:47 p.m..
1>Project "/tmp/q2whkgqf.tbt/restore.csproj" on node 1 (Restore target(s)).
1>Restore:
Restoring packages for /tmp/q2whkgqf.tbt/restore.csproj...
CACHE https://api.nuget.org/v3-flatcontainer/testconsole/index.json
CACHE https://api.nuget.org/v3-flatcontainer/testconsole/1.0.9/testconsole.1.0.9.nupkg
Installing TestConsole 1.0.9.0.
Look at the last few lines carefully. dotnet tool install is trying to install https://www.nuget.org/packages/TestConsole/. Not your local testconsole nuget package!
You can work around it in a couple of ways:
Give your tools a really unique name that doesn't clash with anything on nuget.org or in your organization's nuget feed.
Add a nuget.config that <clear/>s the nuget feeds so only the ./nupkg directory is used as feed when looking to install testconsole.
Building on Omair's answer, the practical steps to solving this problem:
1. Create disable_nuget.config to disable reading from the global feed
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<disabledPackageSources>
<add key="nuget.org" value="true" />
</disabledPackageSources>
</configuration>
note: give it a special name so that it doesn't get picked up by nuget by accident when you don't want it to
2. Install the tool referencing the special nuget configuration
dotnet pack
dotnet tool install --global --configfile disable_nuget.config --add-source ./nupkg TestConsole

ASP.NET Core WebApp not building on Travis CI

Getting the following error on TravisCI when trying to build an ASP.NET Core WebApp.
Could not find project file
/usr/lib/mono/xbuild/Microsoft/VisualStudio/v14.0/DotNet/Microsoft.DotNet.Props,
to import. Ignoring.
Builds on AppVeyor. Is there any way to install the missing file?
Note that I'm new to Travis CI so please include a reference (eg. link/step by step/guide) on how to implement your suggestion, thank you.
After trial and error we've came up with this:
Put these files into the root of your repo https://github.com/aspnet/KoreBuild/tree/1.0.0/template
Copy .travis.yml from a aspnet project e.g. https://github.com/aspnet/EntityFramework/blob/dev/.travis.yml
Remove parts you don't want, like branches and notifications
Make sure your solution and global.json is in the same directory as build.sh
I haven't found any documentation for it, so if it doesn't do what you want, you can just let it install dotnet and do what you want with commands yourself (e.g. dotnet publish)
Old answer:
If you don't solve the problem with xbuild, you can try using dotnet
cli. The install script for RTM is here:
https://raw.githubusercontent.com/dotnet/cli/rel/1.0.0-preview2/scripts/obtain/dotnet-install.sh
Then you use dotnet restore and dotnet build (cd to directory with
project.json)
Change your .travis.yml to this:
language: csharp
install: curl -s https://raw.githubusercontent.com/dotnet/cli/rel/1.0.0-preview2/scripts/obtain/dotnet-install.sh
| bash
script:
- dotnet restore WebApp/src/WebApp/project.json
- dotnet build WebApp/src/WebApp/project.json
addons:
apt:
packages:
- gettext
- libcurl4-openssl-dev
- libicu-dev
- libssl-dev
- libunwind8
- zlib1g
I'm not sure all of the apt packages are necessary. source:
http://andrewlock.net/adding-travis-ci-to-a-net-core-app/
It's also possible to use KoreBuild
https://github.com/aspnet/KoreBuild/tree/1.0.0/template
script: ./build.sh //Add the file to repo

Categories