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.
Related
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.
For some reason I'm getting this error. Below are the specs and then what I did.
Visual Studio 2017 v15.6.2
SQL Server 2008 v10.50.4
I opened the package manager console and added the following packages...
Install-Package Microsoft.EntityFrameworkCore.SqlServer
Install-Package Microsoft.EntityFrameworkCore.Tools
and then I ran
Scaffold-DbContext "Server=ph2srv76;Database=AVDRS;Integrated Security=True;Trusted_Connection=True;" -Provider Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -force
but during the build I get the following errors...
I hate to post the obvious, but in my case (same error) I was targeting specific tables to model (with -t option) and didn't realize that the table names are case sensitive. Doh!
Those are just warnings (yellow), not errors(red) - you can safely ignore them
In case anyone else gets this I solved it by checking and fixing the following:
Make sure that the user id you are using in the scaffold-dbcontext actually has permissions on the tables you want to scaffold. If not the scaffold cannot find them.
Make sure the tables have primary keys or EF cannot scaffold them. Makes sense if you think about it.
After the above the scaffold worked for me!
In my case, I used -table option. I got the same error when I do this:
-Tables "REPORT, REPORT_TYPE, SAVED_REPORT"
The correct way is this:
-Tables "REPORT", "REPORT_TYPE", "SAVED_REPORT"
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]
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
I have been using Entity Framework (5.0) for a while now in a project (ASP.NET MVC in VS2012 Express). Right now, though, I am no longer able to add migrations.
PM > Add-Migration -projectName MyProject.DAL TestMigration
Unable to update database to match the current model because there are pending changes and automatic migration is disabled. Either write the pending model changes to a code-based migration or enable automatic migration. Set DbMigrationsConfiguration.AutomaticMigrationsEnabled to true to enable automatic migration.
I do not know if this gives any clue but the 'Unable to ..." text is displayed in red.
I have tried to enable automatic migration (which makes no sense as I am trying to write the pending model changes to a code-based migration) and that results in the required migration in the database. However this is not what I want because I then I do not have a migration in the project.
I have tried to remove the database and recreate the database. The database is recreated (up to the previous migration) but when I then try to use the Add-Migration I still get the "Unable to update.." error.
Edit
I tried the -force parameter but with no difference.
The contents of my configuration class (I did not change anything after the previous migration):
public Configuration()
{
AutomaticMigrationsEnabled = false;
}
protected override void Seed(Bekosense.DAL.Context.BekosenseContext context)
{
context.Database.ExecuteSqlCommand(Properties.Resources.TriggerAlertMessageDrop);
context.Database.ExecuteSqlCommand(Properties.Resources.TriggerAlertMessageCreate);
context.Database.ExecuteSqlCommand(Properties.Resources.TriggerAlertMessageSentDrop);
context.Database.ExecuteSqlCommand(Properties.Resources.TriggerAlertMessageSentCreate);
context.Database.ExecuteSqlCommand(Properties.Resources.AddDbUsers);
}
Edit 2
I found out that I am able to do an add-migration when I comment the following line out in my DbContext:
//Database.SetInitializer(new MigrateDatabaseToLatestVersion<MyContext, Configuration>());
when I leave the line above active and comment out everything in the Configuration file, it still won't work.
Why is the Database.SetInitializer line causing this strange behaviour?
You can reset the entity framework to solve your problem [But keep it mind it will bring the Migration to the default state]
Note: To take a backup before performing the following
You need to delete the present state:
Delete the migrations folder in your project
Delete the __MigrationHistory table in your database (may be under system tables)
You will find the __MigrationHistory table in your database [Under App_Data Folder]
Then run the following command in the Package Manager Console:
Enable-Migrations -EnableAutomaticMigrations -Force
Use with or without -EnableAutomaticMigrations
And finally, you can run:
Add-Migration Initial
This may also help you
Never use automigrations, that gave me problems in the past (when migrating the database down, use the correct way to do it from the start!)
This line should be in your global.asax:
Database.SetInitializer(new MigrateDatabaseToLatestVersion<MyContext, Configuration>());
And not in your DbContext!
Other tips if the above won't help:
Perhaps you have multiple layers in your application:
Add-Migration 000 -StartupProjectName "NameOfTheProjectInSolutionExplorer" -ConfigurationTypeName "MyConfiguration" -ConnectionString "theconnectionstring;" -ConnectionProviderName "System.Data.SqlClient" -Verbose
Above is the Add-Migration command i use for a multi-layered application.
Same thing for an update of the database
Update-Database -ConfigurationTypeName "SlaveConfiguration" -StartupProjectName "FacturatieMVCv2.Data" -Verbose -script
In my case I've got the same error because I was forcing ObjectContext.CommandTimeout on class DbContext at constructor method during migration.
Try removing it
((IObjectContextAdapter)this).ObjectContext.CommandTimeout = 5000;
This worked for me:
update-database -targetmigration:"0" -force -verbose
add-migration Initial
update-database