Copying project does not retain Entity Framework connection - c#

I'm moving my project from one machine to another. I simply zipped the project folder and moved it to my new computer. My project is an asp.net mvc application with Entity Framework. I have my connection string in my web.config file. When I run my application on my new machine, it has trouble connecting to the database it seems.
I get this error when trying to create a dbcontext
[SqlException (0x80131904): There is already an object named 'Merchandises' in the database.]
But the odd thing is it runs perfectly fine on my old machine.
I executed add-migration command and it says I'm very behind in migrations but this is not true.
Unable to generate an explicit migration because the following explicit migrations are pending: [201802070210548_Initial_Migration, 201802130149472_Added_TrackForm, 201802181945057_Added_DOB]. Apply the pending explicit migrations before attempting to generate a new explicit migration.
Any assistance for debugging this would be greatly appreciated.

You can remove all migrations and add only one that named Initial_Migration ( add-migration 'Initial_Migration' and update-database).
--- reference from github.

Related

Code first migrations when using Filesystem based publish

I am relatively new to this. I am trying to publish my asp.net web application to a production IIS server. In visual studio I select Filesystem based Publishing, since web deploy is not supported by that server.
I use Code First Migrations for my Databases. As long as it is the first time, or if I drop all my tables, the deployments to production work fine. However if I have existing tables with production data, I get the error below -
"The model backing the 'ApplicationDbContext' context has changed since the database was created. Consider using Code First Migrations to update the database"
How do I enable automatic schema updates when my model changes? I have "AutomaticMigrationsEnabled" my Configuration.cs set to true. Do I need to set something in my global.asax or Web.Config? What am I missing?
On my local server I can run Update-Database. How do I make this automatically happen in production whenever I push model updates?
UPDATE:
I was able to get rid of the error in production by following the steps in Using Entity Framework (code first) migrations in production
However I am not sure if this is the best way to fix the problem. Or if I wanted production to keep running this line every time the application starts.
Database.SetInitializer<ApplicationDbContext>(new
MigrateDatabaseToLatestVersion<ApplicationDbContext, Configuration>());
When you use MigrateDatabaseToLatestVersion it will indeed run your migrations for you. So you definitely need that or one of the alternatives like using DbMigrator in code or generating a script (update-database -Script).
These will run the migrations in your folder. The problem is you have AutomaticMigrationsEnabled = true in your configuration. This tells EF to just automatically update your database and does not create the code based migration file.
There are a couple of solutions. First, you could add a manual migration before you deploy (add-migration MyMigrationName) or you could switch your initializer to something like CreateDatabaseIfNotExists and then call the migrations in code as shown above.
See here for a detailed explanation.

Is code first migration automatically run on the server?

I am very familiar with Entity Framework using Database First approach and how to deploy the solution with it.
Basically, in my solution with database first approach, I have a web client project that consumes data access library project that is coded with database first approach.
So, first, I write some SQL Server scripts to add new tables (or make schema changes).
Next, go to the data access library project, using EF edmx designer to update .net from existing database, compile this data access layer, and the DDL reference is automatically updated in the client web project.
When I deploy the solution to the production server:
First, I need to run the t-SQL scripts on the production SQL server
Next, I deploy the 2 updated DDLs (one for the web and 1 for the data access layer) on the web server.
Now, I have a new application that includes a web project and a data access layer project that uses EF Code First approach.
I am new to EF code first approach. I know any time when I change the database schema, for instance adding a new table, I need to run code first migration in the Package Management Console in Visual Studio to let my back-end database instance change/update.
My question:
When I deploy the application to the production, what are the steps I should follow?
How is the production SQL server updated that is created with EF Code First approach?
Is it a automatic process or I have to run the migration manually like I do inside Visual Studio under the Package Management Console?
Thanks.
If you're using Azure then you can configure it has automatic process as shown below.
Else you have to do it manually like this :
You have to create a db script and after that you can run it on your production db.
PM> Update-Database -Script
You can refer this doc : Getting a SQL Script
Another option where I normaley use :
When I need to run migrations aginst the production db,I change my conn string to reflect production db and after that run :
PM> Update-Database
You have several options with migrations.
You can generate a script using Update-Database -Script (as #Sampath notes)
You can run Update-Database -ConnectionString="YourDbString" and it will do it against the production database for you
You can use a migration initializer and on app startup it will use the applications connection string to run the migration. Do this by putting a line similar to this in your initialization routine:
Database.SetInitializer(new MigrateDatabaseToLatestVersion<Context, Configuration>());
Where Context is your DbContext type and Configuration is the configuration class generated when you made the first migration.
See this MSDN article for more information: https://msdn.microsoft.com/en-us/data/jj591621.aspx

Entity Framework : The model backing the 'EFDbContext' context has changed since the database was created

I'm working on a project with EntityFramework and MVC, and I keep getting this error :
The model backing the 'EFDbContext' context has changed since the database was created.
The problem is that there are no migration pending (I've tried to delete/recreate the database, but I still get the error)
I've read several posts on the Web that let me think that I'm not the only one who struggle with this error.
Please find more details below.
Any help will be welcome to understand the situation and fix it.
Project details
I've three projects in my solution:
Core : Models and mappings with the database
GUI.MVC : A web project (using the models from the Core)
GUI.Console : A non-web project (using the same models)
I'm trying keep it "Code First" (I would like to work in the code only, and let EF deal with the database)
Step-by-step
I've deleted the database and the "Migrations" folder in the Core project to start "from scratch".
I run the GUI.MVC project : I get no error while browsing and the database is created "on-the-fly" when I access to the views based on it.
However, if I run the GUI.Console project, I get the error.
I open the Package Manager Console with the Core project as default project (in the dropdown list) and the MVC project (with the connexionstring in the Web.config) as startup project
I run the command Enable-Migrations -EnableAutomaticMigrations. A new folder "Migrations" is created in the Core project. The situation is the same : the MVC project works, the Console doesn't.
I run the command Update-Database, and get :
No pending explicit migrations. Applying automatic migration: 201408071410203_AutomaticMigration. Running Seed method. Now, the MVC project no longer works : I get the error (The model backing...) when I try to access the data. However, the Console project is now working!
If I re-run the command Update-Database, I get No pending explicit migrations. Running Seed method. And I still get the error in the MVC project, and the Console project is working.
Configuration
Nuget packages
Entity Framework 6.1.1
ASP.NET MVC 5.1.2
Visual Studio 2013 Update 2
Thanks a lot !
You can turn on debugger, i would assume the exception will stop at one the dbcontext or dbset, and inspect the dbcontext or dbset variable, find its dbcontext object , and inspect base -> Database -> connectionstring property, then you should see which database it is complaining. Looks like you are deleting the wrong database.

Where is the mysterious EntityFramework database?

In my main project, I have configured a connection string to my database like this:
<add name="DefaultStoreConnection" "provider....">
In my infrastructure project, I have a database context with a default constructor that passes the connection name to the base class:
public DatabaseContext() : base("DefaultStoreConnection") {}
As soon as my application starts, EF generates a 'store.sdf' (SQLCe database) in the application output folder (\bin).
Now, I wanted to reset all migrations and start with a plain database. I deleted the 'store.sdf' in the \bin directory, deleted all migration files and then called in the Package Manager Console:
Enable-Migrations -Force -ProjectName "MyInfrastructureProject" -StartUpProjectName "MyMainProject".
This worked fine, a new migrations configuration class was generated. Then I ran:
Add-Migration Initial -ProjectName....
And then the following line appears:
A previous migration called 'Initial' was already applied to the target database
Where? Where does this migration has been applied to? Where can I reset this 'migration'?
It should be in a folder containing all the migrations, but it's possible that it's deleted after it has been applied to database. You can see list of applied migrations in __MigrationHistory table of your target database. If you wish to rescaffold the database, empty the __MigrationHistory table.
I run to the same problem as you. After a day of google search without a single useful help, i figured it out myself that this is Visual Studio bug where your solution have more than one Mvc projects. The add-migration will check on the older Mvc project to create migration file for your current project (that is why i call it BUG).
To avoid this, you should only use one Mvc project per solution.
Have a look at the app_data folder of your project.

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