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"
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'm tried to Add-Migration in my asp.net core application but migration not working
Please any one give me ans for this what's the issue
Please check this image i added all information reading issue everything i combined into single screen-shot for more clarification
you need to provide a name for the migration just like this Add-Migration V1, after creating the migration you need to run the Update-Database to apply the migration. BTW if there is any build error nothing will work. you need to ensure there is not build error.
I would do this:
1) Remove the Migrations folder in your project
2) Delete the _MigrationHistory table from your database.
3) Run the Enable-Migrations command from your Package Manager Console.
4) Run the Add-Migration Init command to create a migration.
5) Remove all of the code lines in Up() function for the initial migration. (To create an empty migration.)
6) Run the Update-Database command to apply your empty migration.
7) Make changes to your code first model for preparing to adding your real migration.
8) Run the Add-Migration InitNew command to create a new migration.
9)Run the Update-Database command to apply the changes.
Taken from: https://stackoverflow.com/a/44019743/6221069
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.
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"
Code First Environment
I'm trying to update the database from package Manager console. If my domain class changes, I have to drop and create the database. Instead of dropping the database, how can I update the database?
Commands
By using this command, I installed the Entity Framework successfully.
PM> Install-Package EntityFramework
By using this command, it created the Migration file in my project.
PM> Enable-Migrations
By using this command, I may update the table but I have a problem here.
PM> Update-Database
Error
Specify the '-Verbose' flag to view the SQL statements being applied to the target database.
System.Data.SqlClient.SqlException (0x80131904): A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections.
Doubt is here
Sometimes it may update if only one field changes in POCO Class. For example I have updated the more number of Domain class. How can I update the database from Package manager Console?
You can specify connection string via ConnectionString parameter:
Update-Database -ConnectionString "data source=server_name;initial catalog=db_name;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework" -ConnectionProviderName "System.Data.SqlClient" -Verbose
Also you need to use this parameter with the same value for Add-Migration command:
Add-Migration Version_Name -ConnectionString "data source=server_name;initial catalog=db_name;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework" -ConnectionProviderName "System.Data.SqlClient" -Verbose
I used
Enable-Migrations -EnableAutomaticMigrations -Force
then
Update-Database
And this migrated my changes (additional columns) while preserving my test data. I think this is the laziest option while prototyping.
Looks like you have multiple issues. Regarding not wanting to drop and recreate the database, that is determined by your database initializer. If you want to use migrations you change it to MigrateDatabaseToLatestVersion. http://www.codeguru.com/csharp/article.php/c19999/Understanding-Database-Initializers-in-Entity-Framework-Code-First.htm
Second, it doesn't matter how many fields you change, they will be rolled into a single migration based on changes from the last migration.
Third, as the others have pointed out, it seems you have a connection string issue. While you can add that to Add-Migration and Update-Migration I would probably fix it in the application. I set mine in the constructor of my context which points to my config file (web.config for ASP.NET).
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext()
: base("MyConnection", throwIfV1Schema: false)
{
Database.SetInitializer<ApplicationDbContext>(new MigrateDatabaseToLatestVersion<ApplicationDbContext, MyObjextContextMigration>());
}
...
Where to put the connection string?
You do not need to specify it with every command in the package manager console. You can put it in appsettings.json in the project where your DbContext class (read "from DbContext derived class") resides.
{
"ConnectionStrings": {
"MyConnectionString": "Server=yourServer;Port=5432;Database=yourDatabase;User Id=yourDatabaseUsername;Password=yourDatabasePassword;"
}
}
It will be used for migrations.
Important: If you have multiple projects in your solution, you must select the project in the 'Default project'-dropdown (in the Package manager Console) and you must set the project as your startup project (in the Solution Explorer).
Failing to do so, might cause the wrong appsettings.json to be used with an incorrect/different connectionstring.
This was my experience with EF Core 2.1 and probably applies to the other versions of EF.
You need to update SSDT
go to tools> extension and updates > updates > SQL server data tools