How to change the output folder for migrations with asp.net Core? - asp.net

Does anyone know how to change the output directory of the following command?
dotnet ef migrations add Initial --context EsportshubApi.Models.ApplicationDbContext
I tried to add the option:
--content-root-path 'Migrations/Identity'
But that doesn't do anything. There is a --data-dir option as well and something else with directory. But none of them is the output for migrations.
My problem is that I have 2 DbContexts so I want their migrations to be separated.

dotnet ef migrations add Initial --context EsportshubApi.Models.ApplicationDbContext -o YourFolderPath
dotnet ef migrations add
Adds a new migration.
Arguments:
Argument
Description
<NAME>
The name of the migration.
Options:
Option
Short
Description
--output-dir <PATH>
-o
The directory used to output the files. Paths are relative to the target project directory. Defaults to "Migrations".
--namespace <NAMESPACE>
-n
The namespace to use for the generated classes. Defaults to generated from the output directory. Added in EF Core 5.0.
Also here are the common options you can use with this command.
Source

For Package Manager Console run this command:
PM> Add-Migration 001 -OutputDir "Data/Migrations"
My structure is:
.AspCoreProject
-Data
-Migrations
20190721162938_001.cs
MainDbContextModelSnapshot.cs
Update:
For removing last migration use:
PM> Remove-Migration
Note: If the migration is already applied to the database, then you will get this error:
The migration '20190721162938_001' has already been applied to the database. Revert it and try again. If the migration has been applied to other databases, consider reverting its changes using a new migration.
Then run:
PM> Remove-Migration -Force
If your migration is not the last migration. first, rollback to the migration you need by Update-Database then delete all migration classes after that migration.
PM> Update-Database -Migration 001
This will revert all migrations after 001

In EF Core 5.0, you are free to move Migration files and changes their namespace manually. New migrations are created as siblings of the last migration. Alternatively, you can specify the directory at generation time as follows:
.Net core CLI
dotnet ef migrations add InitialCreate --output-dir Your/Directory
Package Manager Console
Add-Migration InitialCreate -OutputDir Your\Directory
EF Core 5.0 documentation

You just need to use -o Or --output option with your command,
To do so, you need to explore to your root project folder, eg: C:\project\SampleAPi\
and use this command
dotnet ef migrations add DbInitial --context SampleAPi.Infrastructure.DbContext -o Infrastructure/Migrations
and then
dotnet ef database update

Related

How to output SQLite database in a different project in EF Core 3

I have a solution with 2 projects
src
|-ProjectA
|-ProjectB
ProjectA is a class library targeting netstandard2.1, it contains the DbContext (with "Data Source=blog.db"), the entities and it has a dependency on Microsoft.EntityFrameworkCore.Sqlite
ProjectB targets a netcoreapp3.1 and has a dependency on Microsoft.EntityFrameworkCore.Design. I just use it to manage migrations because migrations need a framework.
The SQLite database does not exist, so I create the first migration with dotnet tools from the ProjectB
dotnet ef migrations add InitialCreate --project ../ProjectA
and it successfully creates the Migrations folder with the initial one.
Now I want to update the db so that the SQLite *.db is actually created.
If I do this:
dotnet ef database update --project ../ProjectA
the *.db file is created but in the ProjectB. I want the file to be output in the ProjectA but I cannot find a way to do so.
The doc does not seem to mention anything and neither the ef database update --help
UPDATE 1: I have tried to create and update migrations from the ProjectA instead and point to the executable project like this:
dotnet ef migrations add InitialCreate --startup-project ../ProjectB
and it creates properly the Migrations in ProjectA. Now I try to apply them to generate the *.db like this:
dotnet ef database update --startup-project ../ProjectB
and it generates the *.db file... but again in ProjectB! not in ProjectA where I want.
It seems wherever the Microsoft.EntityFrameworkCore.Design package is, the generated database is placed there.
UPDATE 2: Specifying the project when updating database to point to where the DbContext is, didn't work either. It keeps generating the *.db in Project B
dotnet ef database update --startup-project ../Sasw.SimpleBlog.Storage.SQLite.Migrator/ --project ./
I fixed it by specifying a full path at my connection string. It's sufficient because this path should be configurable in settings.
public class DatabaseContext
: DbContext
{
public DbSet<Thing> Things{ get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder options)
{
options.UseSqlite("Data Source=D:\\database.db");
}
}
The only problem left here is how to pass this connection string at runtime by using the dotnet ef CLI. But that seems an open question atm https://github.com/aspnet/EntityFrameworkCore/issues/10750
I know its kinda late for this response but maybe this helps, i haven't tried it.
Have you tried choosing a different default project in Visual Studio's Package Manager Console?

Can't scaffold with ef core for a console application project, doesnt reference .design package

When using Entity Framework Core for a console application i can't scaffold the database.
dotnet ef dbcontext scaffold "Server=;User Id=;Password=;Database="
"Microsoft.EntityFrameworkCore.SqlServer" -c Context -o Models -t Tables -f
Your startup project '' doesn't reference
Microsoft.EntityFrameworkCore.Design. This package is required for
the Entity Framework Core Tools to work.
Ensure your startup project is correct, install the package, and try again.
I've tried to install both Microsoft.EntityFrameworkCore.Design and Microsoft.EntityFrameworkCore.SqlServer.Design. Same problem.
If i set up a new mvc core application i don't get this error. Only when i set up new console applications.
What am i doing wrong?
I ran into a similar problem until I used the Entity Framework Core .NET CLI. Try the following to see if it will work for you:
dotnet new console
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.Design
dotnet ef -h
You should see the EFC CLI Options screen. Do the following to scaffold (replace connection string with your own):
dotnet ef dbcontext scaffold "Server=.\;Database=AdventureWorksLT2012;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -o Model
Once you to that, you should see a Model folder in your project with the class files representing the entities.

A parameter cannot be found that matches parameter name 'Script' [duplicate]

I'm building a MVC application with .Net Core and I need to generate the script of a migration.
With EF6 I did run the command
update-database -script
but when I try to do the same with .net Core is throwing the next exception:
Update-Database : A parameter cannot be found that matches parameter
name 'script'
Do you know if there is an equivalent for EF Core?
As per EF documentation you can use :
Script-Migration
If you want to just script all the migrations you can simply call it from Package Manager console like that. If you want to just script the changes from the last migration you can call it like this:
Script-Migration -From <PreviousMigration> -To <LastMigration>
Be sure to check the docs, there're a few more options to the command.
dotnet ef migrations script --help
Usage: dotnet ef migrations script [arguments] [options]
Arguments:
<FROM> The starting migration. Defaults to '0' (the initial database).
<TO> The ending migration. Defaults to the last migration.
Options:
-o|--output <FILE> The file to write the result to.
-i|--idempotent Generate a script that can be used on a database at any migration.
-c|--context <DBCONTEXT> The DbContext to use.
-p|--project <PROJECT> The project to use.
-s|--startup-project <PROJECT> The startup project to use.
--framework <FRAMEWORK> The target framework.
--configuration <CONFIGURATION> The configuration to use.
--runtime <RUNTIME_IDENTIFIER> The runtime to use.
--msbuildprojectextensionspath <PATH> The MSBuild project extensions path. Defaults to "obj".
--no-build Don't build the project. Only use this when the build is up-to-date.
-h|--help Show help information
-v|--verbose Show verbose output.
--no-color Don't colorize output.
--prefix-output Prefix output with level.
so,you can try
dotnet ef migrations script ver1 ver2
dotnet ef migrations script ver1 ver2 -o ./script.sql
This works in .Net Core 2.1
You can use dotnet core cli to generate script
dotnet ef migrations script
Also you can put this to file with new power shell out-file command.
dotnet ef migrations script | out-file ./script.sql
You can also generate a script to rollback a migration by reversing the parameters to Script-Migration. For example, if you have two migrations, BadLatestMigration and GoodPreviousMigration, you can revert to GoodPreviousMigration by using the following command
Script-Migration BadLatestMigration GoodPreviousMigration
Afterwards be sure to Remove-Migration to remove the bad migration
Remove-Migration
This works in .Net Core 2.2.0
This also generates only the SQL
Update-Database -script -TargetMigration TO -SourceMigration FROM

ef core add-migration separate assembly for data and domainmodel

I have three projects in (VS2017 and ef core) and want to run Add-migration.
Web - Startup
Core - DomainModel - here are the entitys
Data - Context and migrations here. And dependes on ef core
The domainmodel have the entities and I want to have the migrationfiles/ output folder in a data project together with my context file.
I want to avoid having dependecies between domainmodel and entity framework. EntityFrameworkscore only have dependecies to Data.
Any suggestions how to run add-migration with this setup to get the migrationfiles in data instead of core/domainmodel?
Add-Migration -Name InitMigration -OutputDir Migrations -Context myDBContext -Project Business\Core
According to #joakimja the solution was to run:
Add-Migration command without the -Context myDBContext -Project Business\Core arguments.

EF Core Error - No project was found. Change the current working directory or use the --project option

I am using Visual Studio 2015 and dotnet core and trying to develop an EF Core Code First project using Sqlite and this documentation / tutorial, which also uses Sqlite => NET Core - New Database
When I try to add an initial migration from the command line ( I am CD-ed into the folder that my data model project is located in) by issuing the following command
dotnet ef migrations add InitialMigration
...I get the following Error.
No project was found. Change the current working directory or use the --project option.
I even tried using the --project option like so.
> dotnet --project "C:\Shiva\EF\EFCFSqlite.Data.xproj" ef migrations add InitialMigration
but that gives the following error.
Unknown option: --project
.NET Command Line Tools (1.0.0-preview2-003131)
Usage: dotnet [host-options] [command] [arguments] [common-options]
I noticed that the documentation is using .csproj file whereas my Project is showing a xproj file. Also the docs mention something about not using project.json anymore :(
Here's my project.json file.
{
"version": "1.0.0-*",
"dependencies": {
"Microsoft.EntityFrameworkCore.Sqlite": "1.1.1",
"Microsoft.EntityFrameworkCore.Sqlite.Design": "1.1.1",
"NETStandard.Library": "1.6.1"
},
"tools": {
"Microsoft.EntityFrameworkCore.Tools.DotNet":"1.0.0"
},
"frameworks": {
"netstandard1.6": {
"imports": "dnxcore50"
}
}
What has changed? Do we have no choice but to Install Visual Studio 2017 and start from scratch?? Is project.json and all this other stuff no longer honored?
Seems like a massive change to me if that's the case :(
sometimes you need to change the current directory in console/terminal eg:
PM> cd E:\Projects\CrossTest\
PM> dotnet ef migrations add InitialMigration
and
Align your package versions.
Either use preview1 packages or preview2.
Mix of those are not supported.
It simply Means that
YOU ARE NOT IN CURRENT PROJECT DIRECTORY
I was facing the same issue when scaffolding existing database of MySql using this.
Command I was executing:
dotnet ef dbcontext scaffold "Server=123.1.1.1;Uid=abc;Pwd=abc;Database=myDB;Connection Timeout=20;Persist Security Info=False;Port=3306;Allow User Variables=True;Connect Timeout=120;" MySql.Data.EntityFrameworkCore -o Models
Causing the same error , then I checked current working directory inside package manager console and found incorrect.
In my case
Mean I was not in current project directory then after switching directory
cd SSGCApp
Now you are in project directory all good to run the Command.
Instead of:
"tools": {
"Microsoft.EntityFrameworkCore.Tools.DotNet":"1.0.0"
},
try:
"tools": {
"Microsoft.EntityFrameworkCore.Tools.DotNet": {
"version": "1.0.0-preview3-final"
}},
Add the nuget package Microsoft.EntityFrameworkCore.Tools
Add the nuget package Microsoft.EntityFrameworkCore.Design
Right-click your project file, select Edit and then add the following to the ItemGroup that contains PackageReference nodes
<DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="2.0.3" />
(You can find the latest version by finding it in the Nuget Package manager)
Open the Package Manage Console: Tools->Nuget Package Manager->Package Manager Console
Type cd {path where your csproj file resides} (this is important)
Now type dotnet ef migrations add InitialMigration
Just faced similar issue. Fixed by downgrading to 1.0.0-preview3-final
"tools": {
"Microsoft.EntityFrameworkCore.Tools.DotNet": "1.0.0-preview3-final",
}
and changing --project param to --startup-project
dotnet ef --startup-project <PATH_TO_PROJECT_DIRECTORY> migrations add <MIGRATION_NAME>
In global.json I also downgraded version to
"sdk": {
"version": "1.0.0-preview2-003131"
}
This might be a temp workaround before migrating to csproj.
Apparently, it may sound funny, but in my case when I was getting this error I had the server-side of the app running. Basically, make sure that your app is not running at all when trying to create migrations. As I said, for me that was the cure. Might be a bit of advice for those who couldn't fix it by following the marked answer.
Just simply use this command.
Add-Migration InitialCreated -c bodoContext
No need to worry.
The dotnet-ef command has moved.
You will need to add a reference to
Microsoft.EntityFrameworkCore.Tools.DotNet AND
Microsoft.EntityFrameworkCore.Design to your dependencies in
project.json, then add Microsoft.EntityFrameworkCore.Tools.DotNet to the tools section and you should be good to go.
Cited from: http://errummwelluhh.blogspot.com
Add references Microsoft.EntityFrameworkCore.Design and Microsoft.EntityFrameworkCore.Tools
Then run:
dotnet-ef migrations add InitialCreate --project ProjectName
or
dotnet ef migrations add InitialCreate --project ProjectName

Resources