SqlException: Invalid object name 'Movie' - c#

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.

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.

Entity Framework Code First Migrations and Firebird

I'm trying to enable migrations on a Firebird 2.5 database.
I'm using VS2015 and the ADO Driver and Entity Provider are installed and working correctly.
I reverse engineered the database, made the necessary changes to make it work.
I can do the enable-migrations on the Package Manager Console, and add a migration.
When I do update-database this happens:
PM> update-database
Specify the '-Verbose' flag to view the SQL statements being applied to the target database.
Applying explicit migrations: [201705301505265_Initial].
Applying explicit migration: 201705301505265_Initial.
ScriptHalted
If I do a update-database -Verbose I get this:
PM> update-database -Verbose
Using StartUp project 'Visao.Web'.
Using NuGet project 'Visao.Data'.
Specify the '-Verbose' flag to view the SQL statements being applied to the target database.
Target database is: 'D:\Upwork\Fernando\SIGECOM.FDB' (DataSource: localhost, Provider: FirebirdSql.Data.FirebirdClient, Origin: Configuration).
Applying explicit migrations: [201705301505265_Initial].
Applying explicit migration: 201705301505265_Initial.
INSERT INTO "__MigrationHistory"("MigrationId", "ContextKey", "Model", "ProductVersion")
VALUES (CAST(_UTF8'201705301505265_Initial' AS VARCHAR(150)), CAST(_UTF8'Visao.Data.Migrations.Configuration' AS VARCHAR(300)), x'1F8B0800000000000400ECBDDD92DC3
and a lot of character because its trying to add a blob to the database.
The __MigrationHistory database was added to the FDB file:
So I guess it's kind of working.
I have no idea what to do next, anyone?
EDIT
Since everything seems to be created, I think the error might be from the Insert on the Migration Table.
Maybe a bug?
EDIT 2
I created an SQL script with Update-Database -Script and tried to run on IBExplorer and get the following error:
can't format message 13:896 -- message file C:\WINDOWS\firebird.msg not found.
Dynamic SQL Error.
SQL error code = -104.
Unexpected end of command - line 1, column 226.
Even running just the Insert statement is not working.
EDIT 3
Create an issue in their tracker to see if someone else knows
EDIT 4
It seems that the guys responsible for the Bug Tracker page keeps removing the bug.
Anyway, if I change providers, either MSSQL or MySQL, the migrations works.
EDIT 5
This is the first migration created. It is empty because I'm trying to use an existing database, already populated, and now I want to use Code First.
public partial class Initial : DbMigration
{
public override void Up()
{
}
public override void Down()
{
}
}
As Mark Rotteveel said (and he should get points for this answer). You're hitting the limit for a statement size in Firebird. There's not much I can do with it because this needs to be script (even if it's executed directly), so parameters won't work.
Possible workaround would be to create multiple smaller models and use these for migrations. Or always generate the script into file and manually use parameters.

error when using multiple EF migrations / configurations (__MigrationHistory is recreated everytime)

i have 2 different and indipendent dbcontexts and i want to create the db schema (using npgsql/posgresql) with code first migration.
i put in 2 different folder the configurations (with AutomaticMigrationsEnabled set to false) and the 2 initial migration files (once for every dbcontext) using the Add-Migration command line tool.
then i use the command line Update-Database with the first configuration and it works, the db is correctly created with the tables related to the first context.
But when i try to use Update-Database with the other configuration i get an exception because it is trying to create the table __MigrationHistory that already exists.
what's wrong in my code?
i found the error, i don't know if it's a bug of entityframework or npgsql dll but if the dbcontexts use a schema different from dbo (i have all the schema set to 'public', the default postgresql s name) it's necessary to set the same schema also for the history table subclassing the HistoryContext https://msdn.microsoft.com/en-us/data/dn456841.aspx.
the detailed error is that the pseudo code executed bu the migration is
if not exist the table 'dbo'.__MigrationHistory
create the table 'public'.__MigrationHistory

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.

Code first migrations - how to display pending model changes?

I'm using code first migrations. Is there a way to display pending model changes in package manager console before I scaffold a new migration?
The accepted answer tells how to get the SQL for a already scaffolded model change before applying to the database.
The original question regarded model changes pre-scaffolding (i.e. changes in the model since the last "add-migration" before running the next "add-migration" ...)
To that answer i will just say: scaffold anyway, that gives you your preview. By that i mean, run "add-migration preview" or something similar, it will create the scaffolded migration with the model changes that you are interested in. Then just delete if from your solution ...
The point here is that there is no need to "preview" when actually "doing" can be quickly undone. Some might think deleting a scaffolded migration version from the migrations section of the solution would break something, but no it is very well supported.
You can even test scaffold, then create the sql script as Colin suggest in his answer, to get the full SQL. Still nothing has been done at this point, so delete the migration version if you'd like.
There is no way that I know of to view pending changes in the model before scaffolding the migration, but I can't think of a reason not to scaffold the migration using Add-Migration so that the pending changes can be viewed in the migration file. There is no need to apply those changes to the database and the scaffolded migration can always be deleted.
Once the migration is scaffolded, if you use Update-Database -Script entity framework generates a SQL script rather than executing the changes directly.
You can get help on the EntityFramework in the package manager using get-help EntityFramework
And you can get help on the Update-Database command using the following:
get-help Update-Database
get-help Update-Database -detailed
get-help Update-Database -full

Categories

Resources