Can't reverse engineer SQL Server database table - c#

I'm trying to create a Web API. I'm following some examples but I can't get anything to work.
The examples say to use this
Scaffold-DbContext connection_string Microsoft.EntityFrameworksCore -OutputDir Models
I don't want to do all the tables so I looks at the "Package Manager Console" help for the command and am told this
-Tables <String[]>
The tables to generate entity types for.
Required? false
Position? named
Default value #()
Accept pipeline input? false
Accept wildcard characters? false
So I've tried this
Scaffold-DbContext connection_string Microsoft.EntityFrameworksCore -OutputDir Models -Tables dbo.table
I'm changing the names of the connection string and tables. I don't want to do all the tables because there are 70+ tables in this db.
When I try that all I get back is.
"Build Failed"
That's pretty terse so when I stick on -Verbose all I get is
Using project 'ArgusApi'.
Using startup project 'ArgusApi'.
Build started...
Build failed.
A little more verbose, but not much. I was getting more error messages but I cleaned those up to just this.
Any help is much appreciated.

The "Build Failed" message simply means that your project doesnt build. (In Visual Studio) Press F5 and try to build your project. If it cant be built cleanly, then when you run "Scaffold-DbContext" you will get this message.
Usually this happens because your entities/pocos are in some sort of broken state. Delete all your models so they dont break the build and try again.

Related

Retrieve automatic migration fail details

In my ASP.NET Entity Framework 6 project I added a new Model and Controller.
I have automatic migration enabled but allowed data loss disabled.
When I ran the application after these changes the new table was actually created into the db, but the application told me:
Automatic migration was not applied because it would result in data loss
Without any other detail. As read in other questions I tried to issue:
Database-Update -Script
to get the "differences" but nothing happened, just the same error message.
I really don't want to force the update unless I'm sure what it's going to do.
What should I do in order to retrieve the content of the current migration?
I tried to look into the dbo.__MigrationHistory table but the Model field contains binary data.
UPDATE
I was able to decode the Model field using this method, but the edmx file contains just the whole diagram of the db, not the actual commands the the migration would issue.
Furthermore, even if add the -Verbose flag as suggested by the tool itself:
PM> Update-Database -Verbose
Using StartUp project 'MyProject'.
Using NuGet project 'MyProject'.
Specify the '-Verbose' flag to view the SQL statements being applied to the target database.
It does not show the SQL statements...
The message is displayed because you probably made some change to your model that results in a DROP command (e.g. removing property).
To see the script for that specific migration, i.e. the update between the latest migration and the one before it, you can use the following command:
Update-Database -Script -SourceMigration: <migrationBeforeTheLastOne> -TargetMigration: <lastMigration>
as stated in ChW's answer.

SqlException: Invalid object name 'Movie'

I am trying to follow the tutorial from the link below to create an app that shows a list of movies from a database with crud functionality, but I am trying to add a user login.
https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-mvc-app/
I have been trying to figure out how to add and update the migrations for the Movie database. I am able to do it when I follow the tutorial without the user login, but once I add the user login, there seems to be an issue that I am not catching.
After I create the model class, I am trying to apply the following steps for the migration
Goto the command line and access the folder with the project in
it
apply the following commands
dotnet restore
dotnet ef migrations add --context MvcMovie2Context (When I run this command, I get (Missing required argument ''.) error)
dotnet ef database update --context MvcMovie2Context
(This command seems to be working for some reason)
When I run the app and click on the movie link, I get the following error
SqlException: Invalid object name 'Movie'.
System.Data.SqlClient.SqlCommand+<>c.<ExecuteDbDataReaderAsync>b__107_0(Task<SqlDataReader> result)
I have looked through my Model, View and Controller classes to check if I made a typo or a syntax error that would cause the object name ‘Movie’ to be invalid, so I think it means that my Movie database was not created.
I have restarted the project multiple times following the tutorial
I have attached screenshots of the command line errors and browser error. I would greatly appreciate if anyone has any hints or suggestions that they could provide me. Thanks!
I had a similar error even though all the tables were properly created. It turned out that my connection string was wrong.
Since the error is SqlException: Invalid object name 'Movie', that means the table named 'Movie' has not created or the Database you are referring has not created.
To see if the Database or table 'Movie' has created, open SQL Server Object Explorer and check the Database name is the same as in appsettings.json. If the Database or table has not created, you may need a migration.
To migrate, open Tools-> NuGet Package Manager-> Package Manager Console and hit the following commands:
Add-Migration MigrationName
Update-Database
Then check SQL Server Object Explorer again or build and run your project.
Do you have a Movies or Movie table in your database?
Since you say that dotnet ef migrations add --context MvcMovie2Context fails, leads me to believe that your model has not been reflected in the database schema. Also, as far as I know, you need to provide a migration name, which is probably why you are receiving the error.
Please try running the following commands.
1.dotnet ef migrations add "AddedMovieEntity" --context MvcMovie2Context
2.dotnet ef database update --context MvcMovie2Context
Hopefully this time step 1 will run successfully, from there you should see a migration file that includes the schema for the Movie entities. After step 2, you should see the respective table in your database.

How to change database after altering model in MVC?

I'm new to ASP.NET and I'm working on this project that uses MVC. It's a simple website development project, and it uses SQL Server CE (.sdf) as the database.
I would like to change a couple of the underlying models, but that causes errors in the database.
I understand that I would need to change the database, and I know it's possible to create models automatically from the database.
I'm wondering if there is any way to create a database from the models. i.e. I don't mind losing all the data, but is there a way for me to change the models and then create a database that supports the existing models.
I hope that makes sense
Yes it possible to
Here is how you can do it.
There are two approaches to accomplish this task.
Method-1. (Via Package Manager Console)
This approach for the Code First.
Open your project and go to Package Manager Console as follows
Tools--> Nuget Package Manager--> Package Manager Console
First Enable Migrations in your project.Type following in console.
enable-migrations -contexttypename yourContextName
This command will add a Migrations folder in your project inside this folder you will
see Configuration.cs inside this file you will see a seed method
protected override void Seed(YourContext context)
you can use this method to seed your database.
Now run following command in your package manager console
add-migration anyNameOfInitialMigrations
Finally To update the database simply run following command.
update-database
Method-2.
Best approach for Model First.
Open your .edmx file.
Right Click--> on the model and then select "Generate Database From Model"
Make Sure you have proper connection strings in your web.config.

Deleting and updating db after changing model class?

Hi I'm working with the mvc 5 framework in ASP.Net on a course I'm taking at my school, but I seem to have hit a wall.
I want to go back and add a field value to my main model (Student) class, but of course that means the structure of the database has to change (getting errors when I try to run it). I was told this should be doable with the command "enable-migrations -enableautomaticmigrations" typed into the Package Manager Console, but I seem to get an error message saying it's an unknown command when I type it. Or am I supposed to do something different than using these commands?
Here is the error I'm getting when I write the aforementioned command:
PM> enable-migrations
The term 'enable-migrations' is not recognized as the name of a
cmdlet, functio n, script file, or operable program. Check the
spelling of the name, or if a pa th was included, verify that the path
is correct and try again. At line:1 char:18
Any help is appreciated!
I wonder if you tried reinstalling Entity framework Install-Package EntityFramework -IncludePrerelease. Sometimes the Prerelease version is not included. Try that. If not try Update-Database -Force if you already have a database. One last way is to reopening the project after closing everything in VS.
The problem was that my project was located in my dropbox. For some reason my visual studio doesn't like that, moved it locally and everything worked.

The model backing the '--Context' context has changed since the database was created - but db is new production database

I've got this error for the 762nd time but this time I am getting it as soon as I attempt to access my Production site, straight after deleting the 'production' database on Azure and then publishing my site.
The model backing the 'PropertyContext' context has changed since the database was created. Consider using Code First Migrations to update the database
I deleted the database because I couldn't fix this issue any other way but it still doesn't work.
Some important points:
I'm using EF6 and publishing to Azure.
This is 1 of 2 projects/sites that uses the same Repo project. I have no
problems with the other one, just this one.
I have tried publishing the problem project first (after deleting the db) and
second with the same result.
I have tried deleting both WEBSITES and the DB from Azure and starting again
I have tried deleting all migrations and starting with a fresh data model
I have tried the following in my Global.asax (in both projects)
Database.SetInitializer PropertyContext>(null); <-- SO won't let me put the first <
and
Database.SetInitializer(new MigrateDatabaseToLatestVersion<PropertyContext, MyConfiguration>());
new PropertyContext().Database.Initialize(true);
I'm using .net 4.5
Why am I getting this error on a new database and how can I get this site to work?
Just ran into the same error in ASP.Net application. In my case I did not use Code First, but I used standard ASP.Net authentication provider which apparently uses Code First, and authentication was broken because of this issue.
Here is quick and dirty solution is you don't care much about existing user records:
For me the solution was to drop the dbo.__MigrationHistory table, authentication started working fine after that. Be aware! This solution is not for everyone! This will fix the problem, but it is potentially risky.
If you cannot afford to lose data in AspNet* tables:
ASP.Net authentication provider automatically creates tables in your database:
AspNetRoles
AspNetUsers
AspNetUserRoles
AspNetUserClaims
AspNetUserLogings
The tables are empty by default, if you haven't created any new logins for your web site, you can use "quick and dirty" solution above. If you do care about preserving user information or just curios how Code First migrations work, follow these steps:
Open your Web.config file and check the name of the connection string you have for your database. It will be one of the records under <connectionStrings> element.
Open Package Manager Console:
Tools –> Library Package Manager –> Package Manager Console
In Package Manager Console window, use a drop-down to set Default Project. Make sure this is the project that contains ASP.Net authentication provider code.
Execute command:
Update-Database -ConnectionStringName MyConnectionStringName
Replace the MyConnectionStringName with the actual name you looked up in web.config.
As a result of this command you will see a new folder "Migrations" with a bunch of code generated by the Update-Database command. Re-build and re-deploy your app, your new migration code will be executed on startup and would bring the database schema in sync with an updated version of ASP.Net authentication provider code.
When using Code First with Migrations, your database creates a table called __MigrationHistory to track the current schema. When you run your application your Entity Framework will check this table to make sure that the database schema matches your database entities. If they do not match, you will get this error.
To update your database follow these steps:
Open the Package Manager Console (View -> Other Windows -> Package Manager Console) in Visual Studio
In the Package Manager Console Window, there is a drop down with your projects in, make sure it is set to the project that contains your DbContext
Make sure that the project that contains your App.Config / Web.Config file is "Set as Startup Project" (If you have multiple Configs, it must be the one with the Database Connection String defined.
Type Update-Database -ConnectionStringName MyConnString where MyConnString is the name (not the actual connection string) of your connection string in your App.Config / Web.Config
If you get an error like this: "Unable to update database to match the current model because there are pending changes and automatic migration is disabled."
You should enable Automatic Migrations and try again.
To enable Automatic Migrations
In the Migrations folder (in the project with your DbContext), open Configuration.cs.
Make sure the Constructor contains: AutomaticMigrationsEnabled = true;
To stop Entity Framework/DbContext from monitoring changes on your database you could simply delete the __MigrationHistory table in your database. It is then up to you to make sure that the database remains updated manually.
MSDN article here
The solution from this is to use the static method SetInitializer and bind to the context a Null value. If you are working on a Web solution, the best position to write the code is in the Application_Start of your Global.asax.cs file.
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterRoutes(RouteTable.Routes);
//...
Database.SetInitializer<MyContext>(null);
}
I got a similar problem this morning. Suddenly the error appeared and couldn't be resolved:
The model backing the 'ApplicationDbContext' context has changed since
the database was created. Consider using Code First Migrations to update
the database
I have one project for MVC and another project for the model, context and repositories. I've been working on it for weeks but today it said stop.
I have tried to delete database, enable-migration, add-migration and update-database so many times that I've lost count. I've added initializers to MigrateDatabaseToLatestVersion as well as DropCreateDatabaseIfModelChanges. All in vain...
What finally made it work was to move model, context and repositories into the MVC project (not something I was keen on)...then it worked right out of the box without any code changes at all (besides namespaces)! Very strange...
I've read so many blog posts during the day trying to solve this problem. One of them (I don't know which one) mentioned a bug in Visual Studio 2013 where reference to DLL files weren't always updated as they should, suggesting that my MVC project missed out something when I was running add-migration and update-database in my separate project. But it's just a guess.
I'm using EF 6.1 and .Net 4.5.1 in my solution.
Got a similar problem! Answer is here
http://www.asp.net/mvc/overview/older-versions/getting-started-with-aspnet-mvc3/cs/adding-a-new-field
(Rick Anderson)
There are two approaches to resolving the error:
Have the Entity Framework automatically drop and re-create the database based on the new model class schema. This approach is very convenient when doing active development on a test database, because it allows you to quickly evolve the model and database schema together. The downside, though, is that you lose existing data in the database — so you don't want to use this approach on a production database!
Explicitly modify the schema of the existing database so that it matches the model classes. The advantage of this approach is that you keep your data. You can make this change either manually or by creating a database change script.
I have spent some hours trying to solve this problem. One project was working, the other one wasn't.
I had different projects referencing different versions of Entity Framework. In my case, I had a Console app and a Windows Service app, both referencing a third project containing code first classes and DbContext.
After running Update-Package EntityFramework everything worked fine in both projects.

Categories

Resources