I'm after running into a problem with using Database-Migrations on my asp.net mvc project because I am using 2 local databases. I now have 2 databases; 1 which was created on project startup for identity user management like users, user roles etc. (aspnet-IdentityTest-201~). I Enabled-Migrations on this database in order to Seed() an admin member into it and everything was working fine.
The 2nd database was created after this using the code first database approach to store model data. Now my question, since my project already has migrations enabled (on the 1st Db), how do I enable migrations on my 2nd Db also? Currently when I run Update-Database, it targets 'aspnet-IdentityTest-20190707071058'. I would like to be able to run this command for my 'IdentityTest.Models.TestDb' also (with automatic migration enabled).
I'm afraid to run 'Enable-Migrations -ContextTypeName IdentityTest.Models.TestDb' again as the last time I did this, it deleted my current config.cs file which included my Seed() for admins and I was left with a new config file for just the TestDb context. The project also failed to build after this
Could somebody please advise if there a way for my 2 databases to have migrations enabled? Do they have to share the same migrations/config.cs file? If this is not possible, using the code first approach; how do I make my project use aspnet-IdentityTest-201~ Db for storing model information instead of creating a new Db like it did with IdentityTest.Models.TestDb?
Thanks in advance!
First I took a solution where I successfully code firsted a db. I changed all occurrences of my db name and suffix it with 2db. I create another connection and call it {..}2 with catalog name {..}2dbSecond. I then delete my Migrations folder. I split out my context file into two contexts and have DbSet<> included in each appropriately.
typed:
enable-migrations -projectname contosouniversitydal -contexttypename schoolcontext
in the added migrations folder, in configration.cs, added the a seed method
Add-Migration InitialCreateContext1 -ProjectName contosouniversitydal -configurationtypename configuration -connectionstring schoolcontext
Update-database -projectname contosouniversitydal -configurationtypename configuration -connectionstringname schoolcontext
I then do the similar for the other context.
You can use https://coding.abel.nu/2012/03/ef-migrations-command-reference
Enable-Migrations has a -MigrationsDirectory option, so you can split among two different databases.
Related
I am trying to use Migrations in my project but when trying to update the database, only the base migration is applied.
I have a total of two migrations.
The Base migration(initialy created)
CreateNewProperty(Change includes adding a new property to one of the tables)
I see Enable-Migration mentioned in the Microsoft Documentation but it seems to have gone obsolete.
In addition to this, I also a mention of using the following in the Context class to enable latest migrations, but SetInitialier() method is no longer available:
Database.SetInitializer(new MigrateDatabaseToLatestVersion<DatabaseContext, EF6Console.Migrations.Configuration>());
When I try to remove all migrations and bring it to the initial state by executing:
update-databse 0
it fails with the following error:
ALTER TABLE DROP COLUMN failed because column 'test' does not exist in
table 'Item'.
which is basically the update done in the CreateNewproperty migration and this error is expected as this migration was never applied. Why is EF trying to downgrade a migration, when it did not apply it in the first place.
Use below command to Migrate to a Specific Version (Including Downgrade)
update-database -targetmigration:MigrationName
More information visit
https://learn.microsoft.com/en-us/ef/ef6/modeling/code-first/migrations/#migrate-to-a-specific-version-including-downgrade
Is it possible that your snapshot has become messed up somehow? You could try deleting that and then create a new migration (one that you could throw away) to rebuild it. Then try running update-database again.
In order to get rid of writing Migration and Update commands each time your data model changes, you can simply write two command line files as EF CLI and just click them to execute Migration and Update commands. These command files create the Migration name using the date and time of your machine.
For the add migration file set a name such as 01-add_migration.cmd (with .cmd extension) with the following content:
For /f "tokens=2-4 delims=/ " %%a in ('date /t') do (set mydate=%%c_%%a_%%b)
For /f "tokens=1-2 delims=/:" %%a in ("%TIME: =0%") do (set mytime=%%a%%b)
dotnet ef --startup-project ../Product.Api migrations add V%mydate%_%mytime% -o Persistence/Migrations -c ApplicationDbContext
pause
and for the update database set e file name such as 02-update_db.cmd with the content as bellow:
dotnet ef --startup-project ../Product.Api database update -c ApplicationDbContext
pause
You can add other parameters of Migration and Update commands as well.
So in my opinion, if you have created lots of migrations and started changing up the classes during the creation of your app, you might have missed something, which happens to many developers.
If that is your case, you should try to delete the migrations history in the database and the tables that were created using the migrations.
The migrations history table is located in the tables folder of the database and looks like this:
Then delete the migrations folder that you have in your Project.
Search for it in the solution explorer.
It should look something like this:
Next, do what you would do from the beginning.
Add-Migration [Name]
Update-Database
Okay, so this is what worked:
I deleted the database completely and then ran the update-databse command.
On running this, first the base migration was applied and then the second migration. And now when I create a third migration and apply it is working as expected!
I want to create a migration for a second and subsequent databases that's in a class library different from the project that uses it. There is a wrinkle. I will never know the connection string until a user logs in and I can get it from a catalog database (saas).
For the catalog database I used the solution from this site. That was fine - This database has its connection string in appsettings.json and can uses dependency injection.
The client databases are all going to be identical using the same migration. My problem is, I dont know how to create this initial migration from the Package Manager Console..
I did try to run this:
dotnet ef migrations add INITIAL --context APIcontext -s ../Jobsledger.API
and its given me the following error:
No database provider has been configured for this DbContext.
Which I expected.
Given that CodingBlast solution (above) to running migrations in a different class library requires a connection which I don't have and requires the database connection to be registered at startup...
..and given that this migration is to be used by every user database to be created how do I create it and of course use it?
I did answer similar question here.
You can implement IDesignTimeDbContextFactory where you instantiate DbContext with no connection string.
For the different library, you can use --project and --startup-project parameters.
Here is an example what I'm using to generate migrations script:
dotnet ef migrations script --context MyDbContext --output migrations.sql --project "./MyApp.Data" --startup-project "./MyApp.Data"
I deploy to a staging server that I don't have control over and have only been given FTP access. I've successfully used EF6 Code Migrations to create and seed the database on the staging server using the method described here.
I would like to basically do the equivalent of the following, but in code, when I deploy via FTP:
Update-database -TargetMigration:0
Update-database
My goal: I have new seed data to replace the existing data.
Any help is appreciated!
As usual I always figure it out moments after posting a question. (I promise I was looking for a long time before finally posting)
I did not realize you could pass a ConnectionString argument to Update-Database. So basically this was all I needed in the end:
Update-database -TargetMigration:0 -ConnectionString "MY_STAGING_CONNECTION_STRING" -ConnectionProviderName "System.Data.SqlClient"
And then on my next deploy it automatically migrated back to the latest version.
ASP.NET WebAPI app published on Azure, Entity Framework code first.
After publishing with migrations executing on application start (first pic) I can't add new migration and work with database context ("model backing the 'DatabaseContext' context has changed since the database was created" exception). On adding new migration EF breaks with error:
Unable to generate an explicit migration because the following explicit migrations are pending: [migration name]. Apply the pending explicit migrations before attempting to generate a new explicit migration.
Looks like EF doens't see migrations from __MigrationHistory table. I checked this table and last migrations exists.
In web.config there are only one connection string.
If it's important, DatabaseContextWithoutCache inherit DatabaseContext (they have different DbConfigurationType).
After adding null initializer Database.SetInitializer<DatabaseContext>(null); to database context it works but I still can't add any migration.
Why does Entity Framework doesn't see that migration is already appended to database? update-database breaks because there are already tables and columns in db.
EDIT:
In my migration list 2 migrations. I rolled back to init (first) migration and remove second. Then add-migration (now it contains changes from second and new changes) and run update-database. It works.
But EF ignore that db is up-to-date and breaks with "model backing the 'DatabaseContext' context has changed since the database was created" exception.
OMG I DON'T UNDERSTAND
I had this issue recently under VS 2013. If in the Package Manager Console you run the command add-migration {name} (optionally adding -startupprojectname {MyProjectName}) the EF should generate a new migration file for you. If that migration file has any content, then it believes you are not where you should be and you should then run update-database with that new migration in place.
Unfortunately it does seem possible to get caught in a loop with this (it happened to me) and there are quite a few SO Q&As which concern this. Very best of luck solving it.
As the error suggests, there is a migration pending against the database.
Use the following command from the package manager (replace values with your own)
update-database -projectname yourprojectname -connectionstring "yourconnectionstring"
Then, create your new migration....
add-migration yournewmigrationname -projectname yourprojectname -connectionstring "yourconnectionstring"
And finally, run the newly created migration
update-database -projectname yourprojectname -connectionstring "yourconnectionstring"
Ok, so I've read the other threads and I'm still not getting anywhere. I have my project set as Startup, I have a connection string in the App.config. I'm using LocalDb in VS2013.
If I delete my database, it creates it ok, BUT, if I try
PM> Enable-Migrations
it tells me that Migrations have already been enabled in project TestCodeFirst. If I then try
PM> Update-Database
it tells me No migrations configuration type was found in the assembly 'TestCodeFirst', and suggests that I try to Enable-Migrations. I have tried adding the -Force parameter. The Migrations folder has only Configuration.cs, and in that file, I've tried setting AutomaticMigrationsEnabled both true and false, with no difference. I'm not lost, cause I can always delete my DB and rerun, but I don't see any way to make the migrations feature work as advertised. Confession: At one point, I took PM's suggestion and tried deleting the Migrations folder. That may have been a mistake.
I have this code snippet in my Program.cs file (I'm just testing this in a console app):
class Program
{
static void Main(string[] args)
{
using (TestContext db = new TestContext())
{
...
Db.ThisOrThat.Add(stuff);
Db.SaveChanges();
...
}
}
}
The Entity Framework Code First approach creates your database automatically, a table will be automatically added to the database by the Code First that is helpful to record the schema of database synchronization with the related model class. Entity Framework throws an error, the database is not synchronized with the class.
To perform the Code First Migration in the database:
Delete the MDF file of the database
Open Package Manager Console and write the following command
Enable-Migrations -ContextTypeName ConsoleApp.Models.TestContext
It creates the Configurations.csclass, then you can edit your code
After Building the application enter the following command in the Package Manager Console:
add-migration Initial
update-database
Note: If you receive an error then you need to ensure that the mdf file is deleted permanently from the App_Data folder. Otherwise you can go to the SQL Server Object Explorer, expand the localDb server and in the Database option ensure that the mdf file is deleted.
Debug the appliction
You'll need to run the "Add-Migration" command that will actually add the migration that the 'Update-Database' command will run:
Code First Migrations
"Add-Migration will scaffold the next migration based on changes you have made to your model since the last migration was created"