EF Migrations - enable-migrations - c#

So, I need help to configure EF migrations.
I recently connected to a TFS repository and do a 'Get Latest Version' to a project that uses EF migrations. After I get the code I tried to run Add-Migration but VS said that I need to Enable-Migration first and then when I do I got the following error message:
No context type was found in the assembly
Basically, I dont know what to do next. If I got a project from TFS that uses Migration already I can use migrations locally already or I need to enable first? If I need to enable, what I need to do? I tried to point to a project where I have my Web.Config pointing to my database but I don't get any lucky.

for this you should have to enable maigration on your DataAccess project
Enable-Migrations -ProjectName dataAccessProjectName -StartUpProjectName yourWebProject
try to run this command on package manage console

A few checks you can do -
1. Identify your "data project" in the solution. This is project should have a reference to "EntityFramework", a DataContext cs file and a "migration" folder.
3. Build your solution,
4. Set your start-up project to the project which typically has config,
5. Switch to "package manager console" and select the data project under the "default project" dropdown.
6. run "add-migration"

Related

Add Migrations to a class Library

I have a class library that contains my DBContext class and the entity classes.
I am using the class library as a nuget package in other projects - not in the same solution.
My plan is to be able to run migrations from the projects and let the migrations be stored in the context class Library under a folder names "Migrations".
So, after including the nuget package into the web project, i modify my Startup.css as follows:
services.AddDbContext<MyDbContext>(options => options
.UseSqlServer(Configuration.GetConnectionString("MyDbConnection"), m=>m.MigrationsAssembly("MyDbContextLibrary.Migrations")));
When I run this, I get the error message as follows
Could not load file or assembly 'MyDbContextLibrary.Migrations, Culture=neutral, PublicKeyToken=null'. The system cannot find the file specified.
I wish to get a guide on how to go about this.
What I am trying to achieve is such that all the migrations are contained in the DBContextLibrary so that any other project that includes it will have the migrations and can easily just run the "Update-Database" command without having to create separate migrations and another database. The plan is that all the projects can connect to the same database without having each project create their own database.
The project is running on EFCore 5.13 and ASP.Net Core 5
Please note, I already referred to the following SO questions and answer but yet to get a solution
Thank you

dotnet core::Unable to run your project. Ensure you have a runnable project type and ensure 'dotnet run' supports this project

I have been running into an error lately trying to run some code with dotnetcore. When I try to run the project in the console (dotnet run), I get this error.
Unable to run your project.
Ensure you have a runnable project type and ensure 'dotnet run' supports this project.
A runnable project should target a runnable TFM (for instance, netcoreapp2.0) and have OutputType 'Exe'.
The current OutputType is 'Exe'.
FYI, here are entries in the .csproj file
Also, I have the following skds and runtimes installed. Yet, whatever TargetFramework I set in the .csproj, I get the same error.
I found a solution to my issue.
The problem was that I had created the project using Visual studio. Hence, the .csproj project file was not in a suitable format for dotnet core.
To solve the issue, I created an empty project with dotnet core:
mkdir myNewApp
cd myNewApp
dotnet new console
Then, I added to the project all the source files I had created with visual studio by simply copying and pasting them in the app folder. I grouped them in the single directory 'src'. At build, dotnet core automatically finds these files and builds the project with them.
Mine is an Azure Durable function. I got the following error when I try to run it with dotnet cli using the command dotnet run.
Unable to run your project.
Ensure you have a runnable project type and ensure 'dotnet run' supports this project.
A runnable project should target a runnable TFM (for instance, net5.0) and have OutputType 'Exe'.
The current OutputType is 'Library'.
The solution is simple. You cannot use dotnet cli for this. Instead You need to run using the command func start as explained here.
And of course you need to install the azure function tools.
Most probably it is do something with the version you are trying, in my case, I was using .nerstandard 2.0 which was wrong and I changed it to net5.0 and I was able to run successfully.
It looks like this now -
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net5.0</TargetFramework>
</PropertyGroup>
I have experienced the same problem that the project refuses to create an EXE file. It was showing to compile a DLL, yet required an EXE to run.
I was using dotnet core and VS-Code and didnt suspect anything until I tried to rename the project folder to start another with the same name. What I got was greyed out folder/file names for some time about 10 sec with no name change.
Only then I realized: though I deleted "bin" folder, there was an instance of the project somehow running alive but hidden (should have prevented me deleting folder otherwise) and prevents any new EXE to be written.
Solution you might ask, simple: just close/restart IDE completely. Any program spawned with it will be terminated. trying to close/terminate terminals do not work.
Open CMD.EXE and run the following commands:
dotnet new console -o myApp
cd myApp
dotnet run
It works for me.
https://dotnet.microsoft.com/learn/dotnet/hello-world-tutorial/run

Type or namespace name 'MySQL' could not be found VS2017

Currently trying to create a connection to a MySql Database. When I added
using MySql.Data;
using MySql.Data.MySqlClient;
to my class I recieved the typical "The type or namespace name ... could not be found". A little searching made me realize I was missing the MySql.Data.dll.
I used Packet Manager console to install MySql.Data:
PM> Install-Package MySql.Data
I verified that it was installed via Tools > NuGet Package Manager > Manage NuGet Packages for Solutions, but I was still getting the build error.
At this point I figured, since the PM downloaded the .dll I'll just manually reference it via References > Add Reference > Browse > Select MySql.Data.dll.
Great!! The red squiggly went away on my using and intellisense started working for classes inside the MySql.Data namespace:
Fast forward 10 mins, I finish writing my test class and hit Build and error comes back:
So in summary, using PM to install MySql.Data got me no where. Manually adding the reference of MySql.Data.dll got my intellisense to recognize the namespace and classes, but when it comes to building I still get the error.
Pretty stumped. Anyone seen this?
Solved this issue! Turns out the newest MySql.Data.dll is built off of .Net Framework 4.5.2, while my project was using .Net Framework 3.5 Client Profile.
Changing my project's framework to 4.5.2 solved the issue. It's quite strange that VS doesn't give a better error message.
To change your project's framework right click on your project (not the solution), select Properties -> Application -> Target framework. The target framework is a dropdown on that page.
I came to this realization thanks to another stackoverflower question: Namespace not recognized (even though it is there)
In terminal after navigating to your project directory, run the following commands
dotnet add package MySql.Data -v 8.0
In this situation MySQL dll files very new. You can download older dll files and includ in your project. I prefer this version. It works for me MySql.Data.DLL
Downloaded the .dll You'll just manually reference it via References > Add Reference > Browse > Select MySql.Data.dll
I changed the reference of MySql.Data from a previous version to the current one and the error was gone. You can select that by clicking on add reference and then on the left side find recent if you have used it, change it to a current version, in my case it was from 8.0.23.0 to 8.0.25.0
I too had the similar issue. I had 3 projects -namely , Data Access Layer, Business LogicLayer and WebApplication. I went to "WebApplication" project property/Application and change the .Net Framework from 4.6.1 to 4.6
Then again it complained saying, the referenced project has higher framework version, so again i right click on the Business LogicLayer and DataAccessLayer and change the .Net Framework to 4.6 instead of 4.6.1. Now the build is successful without any noise ( no warning/no error).
I am able to successfully publish the source code as well. But still the page is not coming up, the error message in the browser is as below :
Server Error in '/' Application. The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its
dependencies) could have been removed, had its name changed, or is
temporarily unavailable. Please review the following URL and make
sure that it is spelled correctly.
Requested URL: /
Version Information: Microsoft .NET Framework Version:4.0.30319;
ASP.NET Version:4.8.4075.0
But I think this is separate error. Now i am trying to fix this error.

"Build failed" on Database First Scaffold-DbContext

I'm trying to generate classes from a database (EntityFramework's database first approach).
For convenience, I'm more or less walking along with this tutorial:
https://docs.efproject.net/en/latest/platforms/full-dotnet/existing-db.html
I'm at a point where I am running the equivalent of this line of code in the Visual Studio Package Manager Console:
Scaffold-DbContext "Server=(localdb)\mssqllocaldb;Database=Blogging;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -Verbose
This line of code is generating the error (with -Verbose mode on):
Using startup project 'EFSandbox'.
Using project 'EntityFrameworkCore'
Build started...
Build failed.
I see no other options that produce any meaningful output, and I see no documentation on this particular error. If it helps at all, this project does not have a project.json file, currently. Everything is in the .csproj file, which I have not manually edited.
Two most important tips:
[1] - Make sure that your project builds completely before you run a new scaffold command.
Otherwise...
You'll start writing a line of code.
You'll realize a required DB column is missing from your model.
You'll go to try to scaffold it.
Twenty minutes later you'll realize the reason your build (and scaffold command) is failing is because you literally have a half written line of code. Oops!
[2] - Check into source control or make a copy:
Allows you to easily verify what changed.
Allows rollback if needed.
You can get some very annoying 'chicken and egg' problems if you get unlucky or make a mistake.
Other problems:
If you have multiple DLLs make sure you aren't generating into the wrong project. A 'Build failed' message can occur for many reasons, but the dumbest would be if you don't have EFCore installed in the project you're scaffolding into.
In the package manager console there is a Default project dropdown and that's probably where your new files ended up if you're missing an expected change.
A better solution than remembering to set a dropdown is to add the -Project switch to your scaffolding command.
This is the full command I use:
For EF Core 2
Scaffold-DbContext -Connection
"Server=(local);Database=DefenderRRCart;Integrated
Security=True;Trusted_Connection=True;" -Provider
Microsoft.EntityFrameworkCore.SqlServer -OutputDir RRStoreContext.Models
-context RRStoreContext -Project RR.DataAccess -force
For EF Core 3
dotnet ef dbcontext scaffold
"Server=tcp:XXXXX.database.windows.net,1433;Initial
Catalog=DATABASE_NAME;Persist Security Info=False;User
ID=USERNAME;Password=PASSWORD;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection
Timeout=30;" Microsoft.EntityFrameworkCore.SqlServer -o DB.Models
--context-dir DB.Contexts --context RRDBContext --project RR.EF.csproj --force --use-database-names
Note: -force will overwrite files but not remove ones that don't exist any more. If you delete tables from your DB you must delete the old entity files yourself (just sort in Explorer by date and delete the old ones).
Full Scaffolding reference:
EF Core 2:
https://docs.efproject.net/en/latest/miscellaneous/cli/powershell.html#scaffold-dbcontext (this
EF Core 3:
https://learn.microsoft.com/en-us/ef/core/miscellaneous/cli/dotnet
Manually building the project by pressing Ctrl+Shift+B helped me to see the errors that were causing the build to fail.
I know this is old, but I spent a while trying to figure this out today, so I hope this helps someone.
I have a .Net Core project but I want to scaffold my files into a .Net Standard class library. DbContext-Scaffold in the package manager console didn't work for me, but dotnet ef dbcontext scaffold in a regular command prompt did.
I had to install these packages in my class library:
Microsoft.EntityFrameworkCore.SqlServer
Microsoft.EntityFrameworkCore.Design
Microsoft.EntityFrameworkCore.Tools
I had to have a .Net Core project set as the startup project in my solution and that project had to have a reference to my class library. I think that last part is what I was missing that kept me scratching my head for so long.
Finally, I cd'd into the class library from a command prompt and ran this:
dotnet ef dbcontext scaffold "<connection string>" Microsoft.EntityFrameworkCore.SqlServer -o <output folder> -s <relative path to my startup project>
I still had this problem even when I ensured that my project (which had EF Core installed) built correctly. It still failed with the "Build failed." message, which is visible when using the -Verbsose flag.
I had to do this in my case:
Create a throw-away ASP.NET Core web application solution
Add the EF Core NuGet package to the solution
Add the EF Core Sql Server provider NuGet package (because I'm using SqlServer)
Add the EF Core Tools NuGet package
Switch -Project in the package manager console command to point to my newly-created (and EF Core-provisioned) project. The last step was just for good measure, since there was only one project in my throw-away solution.
It seems that this whole process requires an ASP.NET core project (or just a .NET Core project that isn't a class library) somewhere in the solution, presumably set as the solution startup project too.
Make sure your project isn't running, for some reason this command doesn't work while my API is running in the background.
Thanks to the above, rebuilding the project solution solved this. Some crucial caveats for me personally were:
Running the dotnet build was not enough (I had asssumed it was)!
In visual studio menu, Build > Build solution (Ctrl + Shift + B)
I believe I was simply trying to run the dotnet build command while inside a child project (myProject.data)
Rebuilding the parent project (myProject) solution was the key
I hope that helps someone else who was equally confused!
Using VS2017 Preview 3, .NET Core 2 (PREVIEW) I had all sorts of issues, but eventually I took the approach suggested above and created a brand new solution.
Created new .NET Core solution
Edited project file and changed 1.0 to 2.0:
<TargetFramework>netcoreapp2.0</TargetFramework>
Closed/re-opened solution
Then, added the Entity Framework:
In PackageManager console:
Install-package Microsoft.EntityFrameworkCore.SqlServer -Version 2.0.0-preview2-final
Install-package Microsoft.EntityFrameworkCore.Tools -Version 2.0.0-preview2-final
Install-package Microsoft.EntityFrameworkCore.Design -Version 2.0.0-preview2-final
Edited project file, and added:
<DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.Dotnet" Version="2.0.0-preview2-final" />
Then;
Opened the Powershell command prompt and changed directory into Scaffold
project folder
Ran: dotnet ef dbcontext scaffold
"Server=DESKTOP-MB70B7U; Database=ForexForme;
Trusted_Connection=True" Microsoft.EntityFrameworkCore.SqlServer -o
Models
Where you put in your own connection string!
Models is the name of my directory where I put all my classes
Build complete solution and see where it fails. I had some NuGet projects hidden away in a folder that didn't build. Only while rebuilding the solution I found out what the problem was. Everything needs to build or else Scaffold will fail.
If entity-framework returns build failed, most probably you have some kind of error in any of your projects.
Even if the project you are running the command on, is clean and error-free, other projects in that solution can cause the build failed response.
Solution
Rebuild the whole solution. Most probably you'll find that error in solution-rebuild process.
Make sure the project you want to run command on, is selected in Default project drop-down inside Package Manager Console
Re-run the command.
If you use multiple projects in the solution, check the default project in the package manager.
I resolved it with right click on projects and "Unload Project" let only the EF project and run the commands
For me the issue was that I was trying to set it up in a new blank console project inside of the solution, which had no files, so the scaffolding tried to use this project as a startup project and couldn't find Main. I fixed it by adding a new file with an empty main
I has same Build Fails Error...
I after close visual studio and open again it, run Clean Solution and then Rebuild Solution from Build Menus after this Scaffold-Dbcontext build successfully
For me, my project built in Visual Studio but I had to specify a version for "Microsoft.AspNetCore.App" when running Scaffold-DbContext.
So instead of:
<PropertyGroup>
<TargetFramework>netcoreapp2.1</TargetFramework>
<RuntimeFrameworkVersion>2.1.6</RuntimeFrameworkVersion>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.App"/>
</ItemGroup>
I had to have:
<PropertyGroup>
<TargetFramework>netcoreapp2.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.App" Version="2.1.6" />
</ItemGroup>
Make sure your build works fine.
Run the scaffold command from the package console, your command should work:
Scaffold-DbContext 'Data Source=TEST-XY010;Initial Catalog=TESTDB;Trusted_Connection=True' Microsoft.EntityFrameworkCore.SqlServer -Context HOPWAContext -OutputDir TESTModel -Force
I resolved it by stopping my server and then running it again.
This stopped working for me today. So I tried running the dotnet scaffold command from the command line and it worked first time. Don't ask me!!
I had a issue that I have some non-scaffolded code in my DbContext project (partial classes for interfaces) that relied on generated files. As part of the re-scaffold though, I delete all previously generated code and of course this causes the project to fail building and thus scaffolding.
My work around is to have a custom "Scaffold" configuration on the project that simply removes from compilation a whole subfolder where any code-gen dependent files are to live.
If this is a path for you, edit your DbContext's .csproj and add:
<ItemGroup Condition="'$(Configuration)' == 'Scaffold'">
<Compile Remove="NonGenerated\**\*.*" />
</ItemGroup>
and change your command line to include a --configuration Scaffold parameter. A powershell sample of how I do this is as such:
# Run from DbContext project root
$DbContextProjName = "Engine.Common.Dal"
#conStr = "...." #Your ConnectionString here, or loaded otherwise
if (Test-Path "Generated"){
Remove-Item -Recurse -Force "Generated"
}
#Entities/Context in own folder for easy delete then regen, entity-dependant files go in NonGenerated
dotnet ef dbcontext scaffold `
$conStr `
"Microsoft.EntityFrameworkCore.SqlServer" `
--context DatabaseContext `
--data-annotations --force --no-onconfiguring `
--namespace "$($DbContextProjName)" `
--output-dir "Generated" `
--project "$($DbContextProjName).csproj" `
--startup-project "$($DbContextProjName).csproj" `
--configuration "Scaffold"
if (! $?){
throw "dotnet ef scaffold failed!"
}
Make sure you have all packages and press ctrl + shift +b to build the solution. It works to me.
Make sure your project is not running
Make sure your project is compiling
That worked for me.
1-
Make sure the build is successful, to check to build is successful go-to solution explorer and right-click on solution name and rebuilt solution, all project will build successful and good to go.
2-
Install NuGet package Microsoft.EntityFrameworkCore.SqlServer
Install NuGet package Microsoft.EntityFrameworkCore.Tools
Install NuGet package Microsoft.EntityFrameworkCore.Design
check all the versions should be the same for NuGet packages like (3.1.3) and install inside class library if you are following onion architecture.
3-
Try now if still, it failed check db context and reference to class library should be added inside asp.net core web project.

Update-database failing - BadImageFormatException

We have a team of developers working on an Asp.Net MVC5 solution, and often after doing a git pull to get the other developers changes we need to update our local databases with any new Database Migrations (entity framework 6.1.3) which have been added.
We run update-database in the Package Manager Console to update the database. This worked until we changed all the projects to compile x64 output. Which was needed to resolve memory requirements.
However now I am getting :
System.BadImageFormatException: Could not load file or assembly 'My.Data' or one of its dependencies.
An attempt was made to load a program with an incorrect format.
When I run Update-database. I've cleaned down all bin and obj folders before recompiling (to ensure all output would be the same format x64).
It looks like the problem may be that the migrate.exe is not compatible with x64. SO,Original MSDN article.
However this post is for EF5. Is this still the case? And is there a workaround? if not it seems bizarre, its not as if x64 or EF are new additions to Visual studio.
Managed to find the answer.
The problem is that the enable-migrations command appears to have a
hard-coded path where EF looks for built DLLs of your project at
/bin/Debug, no matter what the actual build path is. When you change a
Project to x64, Visual Studio quietly changes your project's build
path to /bin/x64/Debug - while EF keeps looking in /bin/Debug. That
causes this vague System.BadImageFormatException
It's harmless to just change your Project build path to /bin/Debug and
magically, everything begins working like it's supposed to.
https://stackoverflow.com/a/23666717

Categories