I have a working app and database locally. I want to setup a remote database for the remote application.
I thought forcing the environment variable would to it:
dotnet ef database update -- --environment Production
But it says "...The database is already up to date." Checking the remote database, it's still empty.
Now, the appsettings.json and appsettings.Development.json files appear to be working correctly. I confirmed my local application connects to my local database, and my remote application connects to my remote database.
Given that the connection strings are correct in the settings, how do I tell EF to do the thing again but for the other database? I feel like I'm missing something obvious.
So I was just using the wrong environment declaration. Run this before the update:
$env:ASPNETCORE_ENVIRONMENT = 'Production'
I have enabled migrations. I am not using automatic migrations and I do not want to use them.
I have done 3 migrations.
In my development environment I am updating database via VS using the command
Update-Database -verbose -StartUpProjectName EntityFrameworkContext -TargetMigration <MigrationName>
In my devlopment environment, everything works correctly.
Now, I must update the database in production environment. I am using following command
Update-Database -verbose -StartUpProjectName EntityFrameworkContext -TargetMigration <MigrationName> -script
I run the generated script on production database. No error. The table __MigrationHistory looks to be good (I have just some doubt about the column Model that is different from dev environment). In this tabel I have the correct number of rows and the column MigrationId is correctly filled.
The database is exactly the same of the dev database. I have checked it.
I have updated also the program.
But, I do not understand why I still have always the same error:
The model backing the 'PublicAreaContext' context has changed since the database was created. Consider using Code First Migrations to update the database (http://go.microsoft.com/fwlink/?LinkId=238269).
I am going crazy.
Thank you for your help
Migrations is enabled for context 'ApplicationDbContext' but the
database does not exist or contains no mapped tables. Use Migrations
to create the database and its tables, for example by running the
'Update-Database' command from the Package Manager Console.
Can anyone explaing why?
If your dev system is working and prod is not, you can generate a script to bring them back in sync:
update-database -Script –SourceMigration $InitialDatabase
This will create an idempotent script that will test what has been applied and what hasn't. Now use SQL Server Management Studio to apply that script.
https://msdn.microsoft.com/en-us/data/jj591621.aspx?f=255&MSPPError=-2147217396#idempotent
I am very, very new to using migrations, but based on the answer to the SO question Database is not getting created at first time, using the Powershell command Update-Database -Script should give me a script to execute outside of automatic migrations. Yet when I try running that command, I get an error message that says:
Unable to update database to match the current model because there are
pending changes and automatic migration is disabled
I would rather follow Chris Pratt's sage advice - in his answer to the linked question - and leave automatic migrations disabled, but the alternative he offers is insisting on automatic migrations.
I am trying to create the database from scratch, using the CreateDatabaseIfNotExists initializer.
It means there are changes to your current model that haven't been added to a migration.
Try:
Add-Migration YourMigrationName
Update-Database -Script
This will first create a migration with the updated model changes, then you can generate the update database SQL script.
VS 2013 MVC5 code first project.
I’m working through the ASP.NET Getting Started with EF6 using MVC5 tutorial to get up to speed on the latest changes and I’m having a problem with migrations.
In the first module the database is created using a database initializer:
<contexts>
<context type="ContosoUniversity.DAL.SchoolContext, ContosoUniversity">
<databaseInitializer type="ContosoUniversity.DAL.SchoolInitializer, ContosoUniversity" />
</context>
</contexts>
and this connection string:
<connectionStrings>
<add name="SchoolContext" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=ContosoUniversity1;Integrated Security=SSPI;" providerName="System.Data.SqlClient"/>
</connectionStrings>
This works fine. In the Code First Migrations and Deployment module migrations are setup. The initializer is commented out and the name of the DB is changed to ContosoUniversity2:
<connectionStrings>
<add name="SchoolContext" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=ContosoUniversity2;Integrated Security=SSPI;" providerName="System.Data.SqlClient"/>
</connectionStrings>
When update-database is then run from the Packager Manager Console it fails with the error message:
Cannot open database "ContosoUniversity2" requested by the login. The login failed.
Login failed for user 'MyMachine\MyUser'.
I’ve re-run both scenarios several times with the same user and the same results. If I change Initial Catalog to AttachDbFilename=|DataDirectory|\ContosoUniversity2; update-database succeeds (the DB is now in the App-Data folder of the project rather the root of the users profile):
<connectionStrings>
<add name="SchoolContext" connectionString="Data Source=(LocalDb)\v11.0; AttachDbFilename=|DataDirectory|\ContosoUniversity2;Integrated Security=SSPI;" providerName="System.Data.SqlClient"/>
</connectionStrings>
You have to use Initial Catalog when deploying though. The production connectionString is set separately in the Web.Release.Config so that is workable.
The question is why the need for the fix, why doesn’t Initial Catalog work with update-database on the development side?
Update 1:
The problem is not with migrations but with LocalDb
MyUser has full rights in SQLExpress (sysadmin). I can log into SSMS under MyUser and fully manage DBs. I ran several tests. Even though I created the initial DB for the tutorial as MyUser it now throws the login failed error if I rebuild the app from scratch and use databaseInitialzer. If I run VS under Admin both databaseInitialzer and update-database work without any problem. If I then copy the DBs from the Admin's user profile root to MyUser's and then run VS, not as Admin, while logged on as MyUser both the databaseInitialzer and update-database then work if the DB is prior existing.
If I change the connectionString to AttachDbFileName and run either databaseInitialzer and update-database MyUser can create a DB in the App_Data folder proving MyUser has DB create rights. MyUser obviously has full rights to the root of its own user profile. There is something amisss with the LocalDb implementation.
Does any one have any insight on this question?
If you delete the DB file, it still stays registered with SqlLocalDB. If LocalDb gets hung up with can’t attach (after manually deleting the DB file) or Login failed see JSobell’s and CodingwithSpike’s answers here:
ef5-cannot-attach-the-file-0-as-database-1.
Run ‘sqllocaldb.exe stop v11.0’ and ‘sqllocaldb.exe delete v11.0’ from the PM Console
UPDATE:
Easier yet use SSMS. Server name: (local)\v11.0, Windows Authentication. This is really the best way to manage your localdb databases.
I'm working with VS 2013 and EF6.1 .
I got similar kind of error when I work with migration and delete database.
I was unable to recreate database again.
Found that error due to SQLExpress local database instance is running on background and keeping the deleted database connection with it.
following are the steps to handle this situation.
Delete the database files (.mdf and .ldf) files.
Delete Migration Folder from your application.
Delete any database connection to that database from server Explorer data connections.
Go to windows Command Prompt (IF VS 2012 or earlier you have to use the VS Command prompt).
Run "sqllocaldb.exe stop v11.0" (This will stop the v11.0 service)
Run "sqllocaldb.exe delete v11.0" (This will delete the v11.0 service)
Go to Package Manager Console in Visual studio.
Run "Enable-Migrations" (This will create Migration folder and content)
Run "Add-Migration init" (This will scaffold the changes to next migration)
Run "Update-Database" (This will create the database again)
I change Standard Security to Trusted Connection
Server=myServerAddress;Database=myDataBase;Trusted_Connection=True;
in appsetting.json you can write this code
`{
"ConnectionStrings": {
"onlineStoreDB": "Server=.;Database=onlineStore;Trusted_Connection=True"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*"
}`
It worked for me.
Exchange from connection string
Data Source=(LocalDb)\v11.0;
to
Server=.\SQLExpress;
This helped me for Code First technique during migration
This will fix your problem and you can update and add as many methods and properties to the Model as you want
Notes: Step 1{If you initiated your databse as in the tutorial}
From the PM Console:
Enable-Migrations -ContextTypeName ContosoUniversity.DAL.SchoolContext
add-migration Initial
update-database
I'm kind of late but I have encountered the same issue while doing Getting Started with EF6 using MVC5.
The issue appears due to an invalid Database Initialisation in the example.
Change
public class SchoolInitializer : System.Data.Entity. DropCreateDatabaseIfModelChanges<SchoolContext>
to
public class SchoolInitializer : CreateDatabaseIfNotExists<SchoolContext>
and it will create the database with no issues.
Initialisation method that is used in the example does not create a new database by default. Not sure if it is a bug or not.
'PM> enable-migrations
Enable-Migrations is obsolete. Use Add-Migration to start using Migrations.'