I try to create an EntityFramework Core's model with an existing database (doc here : https://docs.efproject.net/en/latest/platforms/aspnetcore/existing-db.html) but I have an error.
When I try the Package Manager method, I have the error :
The term "MY_DATABASE_NAME" is not recognize as a valid command applet [...]
This is the command I execute :
Scaffold-DbContext "'MY_CONNECTION_STRING'" Microsoft.EntityFrameworkCore.SqlServer -outputDir MY_PATH -verbose
And when I try the Command Prompt method, I have this error :
System.NullReferenceException: Object reference not set to an instance of an object.
at Microsoft.EntityFrameworkCore.Tools.DispatchCommand.<>c__DisplayClass2_0.<Create>b__0()
at Microsoft.Extensions.CommandLineUtils.CommandLineApplication.Execute(String[] args)
at Microsoft.EntityFrameworkCore.Tools.Program.Main(String[] args)
Object reference not set to an instance of an object.
Here the command I execute :
dotnet ef dbcontext scaffold "'MY_CONNECTION_STRING'" Microsoft.EntityFrameworkCore.SqlServer -outputDir MY_PATH -verbose
Before this question, I checked :
If I have installed good packages (Microsoft.EntityFrameworkCore.SqlServer, Microsoft.EntityFrameworkCore.Tools and Microsoft.EntityFrameworkCore.SqlServer.Design)
If my project.json was correct (tools, ...)
If my database was online, with good credentials
Succeed with command prompt :
Replaced OutPutDir by o
Removed verbose
Removed single quotes
Command :
dotnet ef dbcontext scaffold "MY_CONNECTION_STRING" Microsoft.EntityFrameworkCore.SqlServer -o MY_ABSOLUTE_PATH
Related
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.
I am trying to use -NoOnconfiguring parameter as part of my scaffold command as below using EF Core 5.0.5 version expecting not to generate OnConfiguring() in my generated DBContext class. But still I am seeing the method generated.
Scaffold-DbContext "data source=TestDBSStage.nreca.org;initial catalog=xxxxx;integrated security=True;multipleactiveresultsets=True" -Provider Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models\TestDBContext -Tables "Table1","Table2","Table3" -ContextDir Models\TestDBContext -Context "TestDBContextScaffold" -NoOnConfiguring -UseDatabaseNames -DataAnnotations -Force
Can someone help me solving this?
Thank you.
I have a multiple DBContexts and DesignTimeDbContextFactory implementation like below.
public class MasterDbContextFactory : IDesignTimeDbContextFactory<MasterDbContext>
{
public MasterDbContext CreateDbContext(string[] args)
{
StringBuilder sb = new StringBuilder();
foreach (var arg in args)
sb.AppendLine(arg);
System.IO.File.WriteAllText("D:\\debug.txt", sb.ToString());
string server = args[1];
string databaseName = args[2];
string connectionString = string.Format(Constant.Connection, server, databaseName);
var optionsBuilder = new DbContextOptionsBuilder<MasterDbContext>();
optionsBuilder.UseSqlServer("connection string");
return new MasterDbContext(optionsBuilder.Options);
}
}
As mentioned here, I apply like this.
Update-Database -Context MasterDbContext -AppArgs 'LAPTOP-E4UBP70J' 'MASTER_USER'
But I don't see all args parameters.
The feature is only available in recent release EF Core 5.0 Preview 6
Flow arguments into IDesignTimeDbContextFactory
Arguments are now flowed from the command line into the CreateDbContext method of IDesignTimeDbContextFactory. For example, to indicate this is a dev build, a custom argument (e.g. dev) can be passed on the command line:
dotnet ef migrations add two --verbose --dev
This work well at 5.0.0-preview.7.20365.15 version.
Adding migration with additional args:
Add-Migration InitialCreate -Context MasterDbContext -OutputDir Migrations\Master -Args 'P1 P2'
Updating migration with additional args:
Update-Database -Context MasterDbContext -Args 'P1 P2'
Here is source
Using Entity Framework Core .NET Command-line Tools version 5.0.7 or newer you can pass custom 'application arguments' into the CreateDbContext method by appending -- to the end of the command, followed by a space and then your arguments.
e.g. dotnet ef database update --context MyContext -- MyFirstArg MySecondArg
See
https://github.com/dotnet/efcore/issues/8332#issuecomment-644918706 which describes how to pass arguments when using both Command-Line and Powershell commands.
Command-Line
The commands will no longer interpret any extraneous arguments as application arguments. Instead, if you want to call a dotnet ef command with application arguments, you must now put -- after you pass in all the normal arguments, followed by whatever you want to the application arguments to be. All arguments after the -- will be interpreted as application arguments. If you need to pass in an application argument which, for instance, contains a space you will need to quote that argument e.g.
dotnet ef migrations add InitialCreate -- FirstAppArg "This is all the second application argument" ThirdAppArg
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]
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);