What can i do, if Add-Migration doesnt work? - entity-framework-core

I have a project with a Data Directory what contains the Directories "Context" and "Entities". In the project level i tried out "Add-Migration Initial". I'm getting there a "Build started" and a "Build succeeded". But i haven't a Migrations Directory with the Migrations. What can happend?

statement add-migration has a switch to specify out put directory.
it maybe has diffrence with your out put directory for do it use "add-migration [-OutputDir ]" with your address of your out put dictionary
For technical information, type: "get-help Add-Migration -full".

Related

How to remove a migration manually in EF core 6 (I don't have the Migrations/ts_migrationfile.cs)?

I'm having trouble with a migration that seems to have been wrongly deleted by EF core.
It says I have to manually delete some file, since the migration file was not found, but I can't find a guide on how I'm supposed to delete that.
I had my initial create migration
I added a new one for creating a couple more columns in a table
I didn't realize that mi project was set to pgsql instead of sqlite
I deleted the migration (never applied database update)
Ef core delete command deleted the migration files on ./Data/Migrations
I set sqlite
I added a new migration
The new migration was on pgsql again
Delete migration tries to delete the (step 2) migration instead of (step 6) migration and fails.
It says No file named '20220308_Migration2.cs' was found. You must manually remove the migration class 'Migration2', hence the question.
My commands for adding and removing and listing the migrations were the followings:
dotnet ef migrations add name -c MyContext -p .\Project.Db\Project.Db.csproj -o .Project.Db\Data\Migrations -s .\Project.Server\Project.Server.csproj
dotnet ef migrations delete name -c MyContext -p .\Project.Db\Project.Db.csproj -s .\Project.Server\Project.Server.csproj
dotnet ef migrations delete name -c MyContext -p .\Project.Db\Project.Db.csproj -s .\Project.Server\Project.Server.csproj
After all done, if I execute the list command, output shows:
Migration1 (pending)
Migration2 (pending)
Where Migration1 is the initial create and Migration2 is the migration applied on step2.
The files I have on Data/Migrations folder are the ones corresponding to Migration1 and Migration3 (step 6)
Another questions.
Where does the list command data comes from? is there a secret database or a hidden caché folder?
If I just delete the Data/Migrations folder, will I be able to start over with the migrations?
Thanks
My problem was on communication between projects. I failed to mention before that I have my solution splitted between projects (as you can see by the commands), and happens that those projects are linked to each other by hard links (Microsoft's mklink -h) to de .dll of the compiled lower layer project.
What happened was that somehow the hardlink between the DB project and the Server project failed, so the Server project was not aware about the changes on the Db project, and it could only see the DB project as it was at the moments the hard link failed.
I finally deleted the reference and added it again. As soon as I did that, the project recognized the real state of the migrations and everything went smoothly.
So (answering my questions), the message was telling me to delete the migration file in ./Data/Migrations. The file was deleted, but the Server project could not see that.
The "cache" was actually the broken hard-link that referenced an old version of the DB project. The list command scans the folder -/Data/Migrations and compares with the database.

Entity Framework Core: Automated DB scaffolding into a class library

Following this tutorial it is possible to scaffold a database context using Entity Framework Core via the command line.
Scaffolding has some strange requirements
it needs an entry point aka main method (no scaffolding into class libraries)
the complete project has to be compileable (before scaffolding)
In my current project I need the model classes in a "shared project" (not directly a class library). The shared project does not have an entry point.
(I currently scaffold a lot since DB engineer updates the database model a lot in a database first approach).
In order to create some automated scaffolding task script I planed to automate the following tasks:
create a new, empty & temporay dot net command line application (it is buildable and has an entry point)
add required packages
scaffold the database context and model classes
move the generated classes to the library/shared project
delete the temporary project
So far I managed to automate the first points.
But I can't figure out a way how to add the ItemGroup DotNetCliToolReference to the xml of the .csproj file.
Is there any dotnet cli command that lets me add the DotNetCliToolReference and not only packages and project-to-project references?
Any other hints for me, please?
Install EntityFrameWorkCore.Sqlserver and EntityFrameWorkCore.Tools from Nuget
In package Manager Console write:
Scaffold-DbContext "Data Source=.;Initial Catalog="dbName";Integrated Security=True" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -Project "Project's class library Name"
As of EF Core 2.1 the reference is included in the .NET Core SDK this means you don't have to add the reference to the temp project.
https://blogs.msdn.microsoft.com/dotnet/2018/05/30/announcing-entity-framework-core-2-1/
The dotnet-ef commands now ship as part of the .NET Core SDK, so it will no longer be necessary to use DotNetCliToolReference in the project to be able to use migrations or to scaffold a DbContext from an existing database.
I have created a quick PowerShell script that is added to the classlib which then creates a temp project and scaffolds the dbcontext and cleans everything up at the end.
param(
[Parameter(Mandatory=$true)][string]$username,
[Parameter(Mandatory=$true)][string]$password,
[Parameter(Mandatory=$true)][string]$datasource,
[Parameter(Mandatory=$true)][string]$catalog,
[Parameter(Mandatory=$true)][string]$contextName
)
$workingDir = $PSScriptRoot;
Write-Host "Project dir= $workingDir";
Write-Host "Creating temp project to run scaffold on";
cd ..
mkdir temp
cd temp
dotnet new web
Write-Host "Done creating temp project";
Write-Host "Scaffolding dbcontext into project";
dotnet ef dbcontext scaffold "data source=$($datasource);initial catalog=$($catalog);user id=$($username);password=$($password);MultipleActiveResultSets=True;App=EntityFramework" Microsoft.EntityFrameworkCore.SqlServer --output-dir Entities --context $contextName --project temp.csproj
Write-Host "Done scaffolding dbcontext into temp project";
New-Item -ErrorAction Ignore -ItemType directory -Path "$workingDir/Entities";
Move-Item ./Entities/* "$workingDir/Entities" -force;
Write-Host "Scaffold completed! Starting clean-up";
cd ..
Remove-Item ./temp -force -Recurse;
cd $workingDir;
Write-Host "Clean-up completed!";
I'm sure the script can be improved but it works great as it is.
The script works as follows:
Let's say we run the script in the classlib directory: c:/test/classlib
Store the current directory
Create a temp web project: c:/test/temp
Scaffold the DBContext
Move the scaffolded items to the classlib (Be aware the script is set up to override the current Entities dir)
Delete the temp project
You would still have to change the namespace to the correct one. Support for namespace on scaffold is currently on the list for 2.2 as far as I know. Hope it helps!
Have you tried my "EF Core Power Tools" - they may be able to help you automate the process?
To add another project as a reference to current use dotnet add reference:
dotnet add reference lib1/lib1.csproj
For packages use dotnet add package:
dotnet add package Newtonsoft.Json

How to change references by command line CodeWarrior?

I have downloaded a project from a repository that refers to another project. I'd really like to build this project with Codewarrior 10.4's command line tools. However, the reference path in my .project file doesn't correspond to the location of the project it references, on my computer. I needed a command-line, programmatic way of changing the reference path to the correct location on my machine. So I tried
ecd -references -project project_pathName -allConfigs -remove wrongReferencePathName
with the intent of then running
ecd -references -project project_pathName -allConfigs -add correctReferencePathName
But the first command gave me a file not found error. So, it looks like I can only remove references to projects that actually exist on my system, and can't get rid of bogus references to projects that aren't even valid locations on my filesystem.
Is there any way to remove a bad reference, one that doesn't correspond to a valid project location, from the command line? If not, can you think of any other way I might approach this issue?
Just for context, the way our company avoids this issue normally is via representing our projects and their references in a .wsd file. We drag-drop the file into the CodeWarrior GUI, and this automatically fixes all the references in all our .project files. The issue is that we can't figure out how to invoke the wsd file from the command line. If you know of any way of doing this, it would actually be much more helpful than an answer to my other question!
I tried multiple options for wrongReferencePathName. Above I tested "file:/C:/Development/DSM33/DSM33_India/DSM33_FS_v02.02/AlphaBoot", but I also tried "C:/Development/DSM33/DSM33_India/DSM33_FS_v02.02/AlphaBoot" and "C:\Users\Ross\Desktop\Round2\DM3\Freescale\DSM33_FS_v02.02\Firmware.project".
They all produced the same error. The paths I'm trying don't exist in my filesystem--I have different paths to the referenced projects in my filesystem--so it kinda makes sense that I'm getting a fileNotFoundException. Maybe it's that the references tool is looking for a .project or .cproject file at the provided reference path and crashes out if none is found.
If this is true, I might try spoofing the bogus filepath in my system and copying over a .project file, but this is a real pain.
It's also possible that I'm just not using the referencedProjectLocation argument correctly--for reference command syntax is
ecd -references -project path [-config name | -allConfigs] ( -list | -add | -remove) referencedProjectLocation [buildConfigurationName]. I'm assuming this argument can only take a project filepath, but if I'm wrong or if there's a different way to identify a project with this argument, I'd love to know!
Here is the error output--not sure the full backtrace will be helpful
Thank you so much on your help for this one!
-Ross

How to specify the folder to create SQL database using dotnet ef

I am using Dotnet EF Core, and have created migrations. When I run
dotnet ef database update
the database is created in my windows user folder.
My connection string is
"ConnectionStrings": {
"ContextConnection": "Server=(localdb)\\MSSQLLocalDb;Database=MyDb;Trusted_Connection=true;MultipleActiveResultSets=true;"
}
How do I get the database created in the project directory? (without having to have the full project pathname in the connection string) Using VS2015 I was able to include |DataDirectory| in the connection string.
These CLI commands can be run from the command line by navigating to the project directory
I think you are trying to run CLI commands directly from user profile hence database is created in your windows user folder.
First, navigate to your project directory by using simple dos commands (e.g. CD)
And then run these CLI commands-
dotnet ef [options] [command]
One of the option-
-p|--project <PROJECT> The project to target (defaults to the project in the current directory). Can be a path to a project.json or a project directory.
For more information refer this link-
https://docs.efproject.net/en/latest/miscellaneous/cli/dotnet.html#dotnet-ef
See if this helps.

Updating database to Migration Configuration

I have pulled down a Visual Studio 2015 project created my another developer. Within the Migrations folder are several Migration Configuration files ...
201601081315335_AddedPersonEntities.cs
201601091532275_AddedDepartmentEntities.cs
201601101145137_AddedPayrollEntities.cs
I would like to update my database to the point of one of these Migration Configurations. However when I try this command ...
Update-Database -Verbose -StartupProjectName MyApp.Api -ProjectName MyApp.Data -ConfigurationTypeName 201601091532275_AddedDepartmentEntities.cs
I get the following error ...
The migrations configuration type '201601091532275_AddedDepartmentEntities' was not be found in the assembly 'MyApp.Data'.
I was expecting it would bring my database up to the same schema at the point that 201601091532275_AddedDepartmentEntities was created. Am I missing something?
Go to visual studio, select your MyApp.Data and check the "Show All Files".
Inside the migrations folder, see if there aren't migrations "outside" the project. If there is, then add them to the project with Right-Click > Include in project.
Do you use TFS?
It happens when you add something (File/Folder) inside a project in your solution and check-in your solution, and your colleague doesn't do correctly the merge on the .csproj file (Which contains all the information about the files and folders inside the project).
WAIT
Ok i think this isn't the problem.
You are specifying -ConfigurationTypeName: don't you want -target: instead?
-ConfigurationTypeName Is used to define the configuration class (Normally contains the seed method).
-target Specifies to where you want to update your database (From the current migration to that specific one, forward or backwards it works anyway).
And, do you insert the models inside MyApp.Data or MyApp.Models?