ASP.NET core 2.1 Database-Migration - entity-framework

I have following PROJECT structures.
While adding Migration, it does not recognize my Project"Ravangla.WebUI" directory, which is not in the same directory
My Add-Migration command as follow:-
Add-Migration initial -context RavanglaDbContext -p Ravangla.Persistence
Error:-
The directory name 'C:\Ravangla.Client\Ravangla..WebUI\' does not exist.
Parameter name: path
It does not show correct path first of all as you can notice above: "Ravangla..WebUI", it has two [..], which is not true.

Related

Scaffold Views with Scaffold-DbContext from SQL Server

I have tried to scaffold two views from a database in a SQL Server. Code in .Net 5.0.
Scaffold-DbContext "conn-string"
Microsoft.EntityFrameworkCore.SqlServer
-OutputDir Entities -ContextDir .
-Context MyContext -UseDatabaseNames -Force
-NoPluralize -NoOnConfiguring -Tables View1,View2
This runs without error but no entities for this views are generated and I get a message:
Unable to find a table in the database matching the selected table 'View1'.
Unable to find a table in the database matching the selected table 'View2'.
How do I use Scaffold-DbContext to get these two views?
Aside from referencing the db schema, you could be stuck with this error because the actual project itself does not compile.
I commented out all the code associated to the DbContext model, and ran the following equivalent Scaffold command.
Scaffold-DbContext "Server=MyServer;Database=myDb;user=theUser;password=thePwd;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Entities -ContextDir . -Context MyContext -UseDatabaseNames -Force -NoPluralize -NoOnConfiguring -Tables <<your database view>>
The command ran successfully and created my class in the root folder. I then moved it into my Models folder and went from there. That is optional of course.
There is more info here as to why you need to make sure the solution compiles before you run the scaffold command.

How to deploy the Sql files to Dedicated Server with Azure Devops Pipeline CI/CD

I am working on Azure DevOps CI CD Pipelines. The project's Backend is Dotnet Core, Frontend is Angular 8 and for Database, we used Entity Framework code-first approach. I was able to add Front and back end in pipelines. Now I am stuck with database deployment. since I was also unable to find any dedicated article.
The project is consists of Multi Context and Multi-Project. Reference folder structure
At local we usually run this command to generate migration and it works fine.
Add-Migration -Context ABCCompanyContext AddCompanyTable
Now, in Pipeline i have added the following command which I get from stackoverflow it self. but it didn't work. But from the error. it seems like I am really close
Pipeline Command
dotnet tool install --global dotnet-ef dotnet ef migrations script -i
-o $(Build.ArtifactStagingDirectory)\Migrations\migrate.sql --project **/ABC.Company.Data.csproj --startup-project **/ABC.Company.Api.csproj -i -o $(Build.ArtifactStagingDirectory)\Migrations\migrate.sql
Error Log
2020-12-24T06:49:27.0265041Z ========================== Starting
Command Output ===========================
2020-12-24T06:49:27.0688206Z ##[command]"C:\windows\system32\cmd.exe"
/D /E:ON /V:OFF /S /C "CALL
"D:\a_temp\f3a33029-4f61-404f-9b64-c73c5296123a.cmd""
2020-12-24T06:49:32.9358440Z You can invoke the tool using the
following command: dotnet-ef 2020-12-24T06:49:32.9359182Z Tool
'dotnet-ef' (version '5.0.1') was successfully installed.
2020-12-24T06:49:38.4701578Z System.IO.IOException: The filename,
directory name, or volume label syntax is incorrect. :
'D:\a\1\s*\obj' 2020-12-24T06:49:38.4702878Z at
System.IO.FileSystem.CreateDirectory(String fullPath, Byte[]
securityDescriptor) 2020-12-24T06:49:38.4703503Z at
System.IO.Directory.CreateDirectory(String path)
2020-12-24T06:49:38.4704199Z at
Microsoft.EntityFrameworkCore.Tools.Project.FromFile(String file,
String buildExtensionsDir, String framework, String configuration,
String runtime) 2020-12-24T06:49:38.4705029Z at
Microsoft.EntityFrameworkCore.Tools.RootCommand.Execute(String[] _)
2020-12-24T06:49:38.4705729Z at
Microsoft.EntityFrameworkCore.Tools.Commands.CommandBase.<>c__DisplayClass0_0.b__0(String[]
args) 2020-12-24T06:49:38.4706399Z at
Microsoft.DotNet.Cli.CommandLine.CommandLineApplication.Execute(String[]
args) 2020-12-24T06:49:38.4707003Z at
Microsoft.EntityFrameworkCore.Tools.Program.Main(String[] args)
2020-12-24T06:49:38.4707626Z The filename, directory name, or volume
label syntax is incorrect. : 'D:\a\1\s*\obj'
2020-12-24T06:49:38.6646502Z ##[error]Cmd.exe exited with code '1'.
2020-12-24T06:49:38.7627325Z ##[section]Finishing: Build EfCore
Migrations
The error message,
System.IO.IOException: The filename, directory name, or volume label syntax is incorrect. : 'D:\a\1\s\*\obj'
The path string contains the character '*'. Normally this character is not available in file name and folder name.
As the introduction from the docs about .NET Core CLI, the values of the options '--project' and '--startup-project' are the relative paths to the project folders.
According to my test, in the 'dotnet ef' command, it seems does not support wildcard patterns.
When I use wildcard patterns to set the path values, it always return the same error message.
System.IO.IOException: The filename, directory name, or volume label syntax is incorrect. : 'D:\a\1\s\**\obj'
However, when I directly provide the complete relative paths instead of using wildcard patterns, the error disappears.
So, I recommend you directly use the complete relative paths to the project folders.

EF Core 2.0 scaffold-dbcontext Find ConnectionString in another project

I am using the EF Core 2.0 CLI command scaffold-dbcontext to reverse engineer poco classes from an existing DB (database first). The project that contains my appsettings.json file with the ConnectionString is different from the project that holds the poco classes generated by scaffold-dbcontext.
How can I get the scaffold-dbcontext command to find the ConnectionString in the appsettings.json file of another project?
As stated in this you can now specify your connection string to be named, which looks like name=MyConnectionString. The name of your connection string corresponds with the one defined in your appsettings.json. Example:
Scaffold-DbContext -Connection name=MyDB -Provider Microsoft.EntityFrameworkCore.SqlServer
where in appsettings.json you have something like this:
"ConnectionStrings": {
"MyDB": Server=mydb.database.windows.net;Database=mydb;Trusted_Connection=True;Encrypt=True;"
}
As of the time of this post, it doesn't appear that the scaffold-dbcontext command supports a appsettings.json connection string lookup. In other words, you must explicitly type the full connection string using the scaffold-dbcontext cli syntax:
Scaffold-DbContext -Connection "Server=(localdb)\ProjectsV13;Database=MyDbName;Trusted_Connection=True;" -Provider Microsoft.EntityFrameworkCore.SqlServer -OutputDir Model -Context "MyDbContextName" -DataAnnotations -Force -Project MyEntitiesProject -StartupProject MyEntitiesProject
Not directly related to the OP, but just as a word to the wise... using the StartupProject option is helpful so you don't have to switch the Startup Project in Visual Studio to your entities project (e.g., MyEntitiesProject) in order to run the scaffold-dbcontext command.
There's a good link detailing the scaffold-dbcontext command options here.
Also be sure to have the following packages installed in your project in order to use the scaffold-dbcontext command in the nuget package manager console:
Install-Package Microsoft.EntityFrameworkCore.SqlServer
Install-Package Microsoft.EntityFrameworkCore.Tools
Install-Package Microsoft.EntityFrameworkCore.Design
For me both answers was usefull. I wanted to generate the context in another project, so it was required to specify the startup project and select the project where I had to generate the context. So I use:
Scaffold-DbContext -Connection name=DefaultConnectionString -OutputDir DataModel -StartupProject NameofTheProject.API Microsoft.EntityFrameworkCore.SqlServer
It can be done by using -StartupProject option in Scaffold-DbContext and making startup project reference Microsoft.EntityFrameworkCore.Design package (only caveat).
Example
Project DB: will contain EFCore autogenerated classes
Project API: contains appsettings.json with connection strings (must reference Microsoft.EntityFrameworkCore.Design)
Execute in the package manager Console
Scaffold-DbContext -Connection "name=<connection string name>" -Provider Oracle.EntityFrameworkCore -OutputDir EFModels -Context <DbContext class name> -Project DB -StartupProject API -Force
[if something is wrong you can have detailed logging with -Verbose option]

What are the rules for expected values to the dotnet ef commands?

In an ASP.NET Core application with migrations, running update database gives the following output. It works, and the verbose output displays the default values for a variety of options.
dotnet ef --verbose database update
Setting the data directory to 'C:\temp\bin\Debug\netcoreapp1.0\'.
Invoking dependency command 'Microsoft.EntityFrameworkCore.Design' in project '2016-101DP-TreeGame-Auth'
Running C:\Program Files\dotnet\dotnet.exe exec
--runtimeconfig C:\temp\bin\Debug\netcoreapp1.0\temp.runtimeconfig.json
--depsfile C:\temp\bin\Debug\netcoreapp1.0\temp.deps.json
--additionalprobingpath C:\Users\me\.nuget\packages C:\Users\me\.nuget\packages\Microsoft.EntityFrameworkCore.Design\1.0.0-preview2-final\lib\netcoreapp1.0\Microsoft.EntityFrameworkCore.Design.dll
--assembly C:\temp\bin\Debug\netcoreapp1.0\temp.dll
--startup-assembly C:\temp\bin\Debug\netcoreapp1.0\temp.dll
--dispatcher-version 1.0.0-preview2-21431
--data-dir C:\temp\bin\Debug\netcoreapp1.0\
--project-dir C:\temp
--content-root-path C:\temp
--root-namespace temp
--verbose update database
Process ID: 12544
Finding DbContext classes...
Using context 'ApplicationDbContext'.
Done.
When I try to run the same command with options, the CLI complains that my options have "unexpected values." Here are two examples.
dotnet ef --data-dir C:\temp\bin\Debug\netcoreapp1.0\ --verbose database update
dotnet ef --data-dir "C:\temp\bin\Debug\netcoreapp1.0\" --verbose database update
Both tell me this:
Microsoft.Extensions.CommandLineUtils.CommandParsingException: Unexpected value 'C:\temp\bin\Debug\netcoreapp1.0\' for option 'data-dir'
at Microsoft.Extensions.CommandLineUtils.CommandLineApplication.Execute(String[] args)
at Microsoft.EntityFrameworkCore.Tools.Cli.Program.Main(String[] args)
What are the rules for expected values to the dotnet ef commands?
There are two layers. dotnet-ef reads metadata from the project (and builds it) then calls ef using that metadata (including the output assembly paths). You cannot specify the following options from dotnet ef since they are determined for you.
--assembly
--startup-assembly
--data-dir
--project-dir
--content-root-path
--root-namespace
The rest of the options that show up in dotnet ef --help can be specified on dotnet ef.
This should get better as part of issue #6592.
Here is some documentation about dotnet ef.

ConfigurationType error when using Entity Framework migrate.exe with multiple migration configurations

In my solution, I have a Data project that contains multiple Entity Framework 6.1.3 migration configuration classes. My goal is to run Entity Framework migration steps - for one of them, against an existing database - from TeamCity (or, to simplify, from a command line).
The migration configuration class I am using is the following:
namespace MyProject.Data
{
public partial class MyCustomMigrationConfiguration :
DbMigrationsConfiguration<MyCustomContext>
{
public MyCustomMigrationConfiguration()
{
AutomaticMigrationsEnabled = false;
AutomaticMigrationDataLossAllowed = true;
MigrationsDirectory = #"Migrations\MyCustomContext\MigrationSteps";
}
}
}
I can successfully run the following command from Package Manager Console in Visual Studio:
Update-Database -Verbose -StartUpProject Web -ConnectionString '-my
connection string here-' -ConfigurationTypeName
MyCustomMigrationConfiguration -ConnectionProviderName
'System.Data.SqlClient'
I want to do the same thing from a command line, so I run this:
migrate.exe MyProject.Data.dll "MyCustomMigrationConfiguration"
/startUpConfigurationFile=MyProject.Web.dll.config
/connectionString="-my connection string here-;"
/connectionProviderName="System.Data.SqlClient" /verbose
However, I get the following error:
ERROR: The migrations configuration type
MyCustomMigrationConfiguration was not be found in the assembly
‘MyProject.Data'.
Any suggestions on how to fix this, please?
You can specify the directory where are all the dependencies (assemblies) needed to run your code. You can do that by using the /startUpDirectory option, as explained here:
Specify working directory
Migrate.exe MyApp.exe /startupConfigurationFile=”MyApp.exe.config” /startupDirectory=”c:\MyApp”
If you assembly has dependencies or reads files relative to the working directory then you will need to set startupDirectory.
Found the solution (I ended up downloading the Entity Framework source code from http://entityframework.codeplex.com/ and debugging the migrate console application).
Apparently, all the dependencies of MyProject.Data.dll need to be copied in the same folder with it and migrate.exe, otherwise the Entity Framework migrate.exe tool will throw the misleading error message above.
Entity Framework could really use better error handling and a clearer error message in this case.
As a reference to Entity Framework devs: the following code in TypeFinder.cs was returning a null type because the dependencies of MyProject.Data.dll were not copied in the folder of migrate.exe:
type = _assembly.GetType(typeName, false);