Encoutering problem when updating second migration with a different name in asp.net core - asp.net

I am trying to add and update second migration in asp.net core with a different name from Initial Migration, but during update-database the error says There is already an object named 'Values' in the database. How can I can I update the new Entity and not update the Values object.

it seems there is a problem in migration process,
run add-migration command in "Package Manager Console"
Add-Migration Initial -IgnoreChanges
do some changes, and then update database from "Initial" file:
Update-Database -verbose
For more details refer this link
https://stackoverflow.com/a/43687656/495455

Thanks for help, I finally find a solution. I had to remove all migrations and it worked perfectly with different name for the second migration

Related

How to add a record to __EFMigrationsHistory without actually running the migration in EF Core

I have an issue where I have an existing database which where I have mapped over only certain entities to use with EF Core (the DB has 100s of tables and I dont want classes for all of them.
I scaffolded the starting stage like this
dotnet ef dbcontext scaffold .. etc etc
Where I specified specific tables with the connection string.
I then created an initial migration to snapshot the starting stage with
dotnet ef migrations add Initial
I now want to add a new table based on a new entity. So I created a second migration using
dotnet ef migrations add NewTable
But when i run this using..
dotnet ef database update NewTable
It attempts to add the tables in the initial migration! because I havent ran that migration, so I have no records in __EFMigrationsHistory. But I dont want to run the first migration as I already have the tables which were scaffolded! Initial was just to create a snapshot which is what I thought you have to do.
So is there some way to make it think Initial has already been run? By putting something in
__EFMigrationsHistory? Then I can run the NewTable migration without getting "object already exisits".
Thanks
It ran my latest NewTable migration fine after I removed the previous one, otherwise it was still trying to add objects from the initial migration resulting in "Object already exists".
I find this strange as the statement
'dotnet ef database update NewTable'
specifies which migration I wanted to run, and shouldn't run initial again. Anyway this fix worked fine.

Update-Database doesn't create db

I have tried to create a db using Update-Database; however, although everything seems to be fine, I don't see any new database created when I click on the SQL Server Object Explorer.
PM> Update-Database -Verbose
Using StartUp project 'Stats'.
Using NuGet project 'Stats'.
Specify the '-Verbose' flag to view the SQL statements being applied to the target database.
Target database is: 'Stats.DataAccess.StatsDbContext' (DataSource: .\SQLEXPRESS, Provider: System.Data.SqlClient, Origin: Convention).
Applying explicit migrations: [201511280800579_Initial].
Applying explicit migration: 201511280800579_Initial.
INSERT [dbo].[__MigrationHistory]([MigrationId], [ContextKey], [Model], [ProductVersion])
VALUES (N'201511280800579_Initial', N'Stats.Migrations.Configuration', 0x1F8B0800000000000400ED5CCD6EE33610BE17E83B083AB545D64AB287B681BD45EA245BA31B278893456F0123D18E508952452AB551F4C97AE823F5154AEA972229899265C31B040B0489480EE7E71BCD7038DAFFFEF977FCD3DAF78C171861374013F364746C1A10D981E3A2D5C48CC9F2DD0FE64F1FBEFE6A7CE9F86BE3733EEF3D9B4757223C319F0909CF2C0BDBCFD00778E4BB7614E060494676E05BC009ACD3E3E31FAD93130B521226A56518E3BB1811D787C91FF4CF69806C18921878D781033D9C3DA7238B84AA31073EC421B0E1C45C1040F0E80210706EDB1063D338F75C40F958406F691A00A180CEA05C9E3D60B8205180568B903E00DEFD268474DE12781866DC9F95D37505393E658258E5C29C941D6312F81D099EBCCF346389CB7BE9D72C3447757749754C364CEA447F13F323FD79F90211310D71B7B3A917B199B27E47091917E251B1FCC848261D1578A0B061FF8E8C69EC9138821304631201EFC8B88D9F3CD7FE156EEE83DF219AA0D8F3781E299774ACF2803EBA8D8210466473079719E7B30BD3B0AAEB2C7161B18C5B938A3443E4FDA969CCE9E6E0C983050438F1172488E04788600408746E012130A2169C393051A2B4BBB0D76DE022F21978316CDBB399CE34826C7FAAFD8210FBFD9EFA4A675A0FA1D39FD61CBCB8AB443502550602D3B8835E32889FDD30F5BC121D8FE994AB28F0EF028F875D32F2B808E2C8662C05CAE17B10AD20D167E8D6031B18B5B0944F5231958E35B0954D503136B64A276B75BDFE5EF7E670E25E541F1149A1BCA59B1CBECB9DFF0936F710F8B5187F2C6754015E0C28D15D8E76F5B95F021F367354CE1038CA07D41C15A35B395BBA711F67632BDF9C4DDC6B0E4A3FA319154D0D4DE31AAC3F41B422CF1393FE4ACDECAEA1933FC93878402ECD24E92212C5AFC00FD3388095A0CF63840079EE7101E91CF0FC58EE0CBDE09E07B73E804FD7BE415EDCEBCA8D30D90BEE3F813D6D74F80E561B5234BC4B0C272ACFD3F1AE738C03DB4D18A8B857BA7955904BE4180D9CA4E62CF9A736A5DEE486D47FE8C613F33B49336A82C58BA324986AA24AEE78343A1165E4A46916B29A46D471559353947CA569AEBE98EA3464E78216D949235F72AAB2A5A05276B36B41B9F3581363AAC35955D4AC6AD04D5EC5A1AE458303099CB95B3B6FE2D16F30A1852363EBABA083E0E96B6B1A20025C1ADDCAF310C1174FEC315CABEA3B0F1866E900CEC285280523BB80242398C841739DF22D296B46524495049B5947A17531F307D5E2D44F5A1617999AB43C57BF4080D3B548258B3ADC0C455012139EE6C850B0CB716AE991C811C591C834256653559134C4154E92B2C00D3142234A701C67C06810591D177625747958AD115A1D2F34224677A1A518B123A1F9529D5AEABAE0A1133E38A6F317498BE08A60D1A6BCAD24CF5F044DB2ABE2885E24E92BBF1037DA5F140D3AC833DC225494B72A567AAD925FBF5835F72FE36B1086F430C2DDC7644F8C457A19337DB7E87E4FE1A7342C1B2BAE2B0A6E8B9DE8410EACA0304AB7A69C26A73476AC7D02EC9C31757C699A10186BE246BE5925F6C906CB83493E9DFDCEC55FFE845D8649814CA9C42B2A974F6724224201ED356B932B31E0814871369E065EECA3BAF375D36AFEFA82A7C23FD7A7563968F2E42A03FAF42A874D9E5E6540A637B604458B06B5248B0ABE25E2430B3DE9BB6A6BF0F4C4CDBE20C315E07922DCE337C06802260DEB5B0146959C680046BD6C3780496B5CFCFAB9E21CF006935A98E419C0564051A7341A50A95BB81BB070E5579E08F7589F565960E549954FDF00280E57534A150AB343712BD0B2797A606219B1F2CAA572F495B5A185BF84840A844C19C5B6DD38CAB2FD9E1C756686E6B08E9B14BC6698D5D88BFABA869CE239A1B3DD85EA404BF2C2CDD44952147A5656007A6ABA203380FD95C58D83424083B4C3A0A02C97B4A1A09CB90D0AC492484F6D176486428158ED39281434483B080AF8FA91CE31389BAA7DD4AD51BA5C26EAA9F584C44048900B600705851A510784415E4CD302423E791828542B663DF59E1119140ED58AE04101A256DC7648484545714A919B16C545A18838CE0A7AED9DDE52852F9D621A54F817D749AA7B1B4CA09FE06CB4F8C39B7A6E7231954FB806C85D424CD25E15F3F4F8E45468173F9CD66D0B63C753144495FDDB55ABEDA1E3C6656A6DEDA9E9D84522774D27DB6CDFC0C94E4FECFB8253060568BBE9470BDF0FD1E63214E9E2A5CC092E5DDACE9003D713F3AF64CD9931FBED315B7664DC4414DF67C6B1F137BFB54E1F10E7FDDDF62E16EAEFDEAD3FFA75A05A6A4D1E0A325F26D02BC7916E80E3966E03F84A2ADC8D036EE90E40AF6841FA52413F0725DED10B88EC67107DE383F5B75D8DF52580BC6B67EEEB30B1D412BB959DC5B6D7570F1A9974CF77D260EFA37EADAE65E5A753E76285067F5EECD8224B5D04460CC1C0A367104C227A0A91EADFB7918B6C37041ECFB37C04D3713BA6BE829C3872014388983F55E5D2D9A9A112555015FCBF4DF4C1DB7D8730F547CEC73B74CE1EB4996BAEE7E57D5A0ACFFB32746BBBF39BA1B734744B6D794F86D66CF7EED1862DD1C83A80FB754CF7B2B9B62D06B0795DE396BC59431979AF466F6979D70EB80769FA0E6175AFC66F2C1B0F6E7E75E3BFDC0629DA4E6ECACF6CD5D4DA9F965A69AEFB145053A79965312C77A1AA76A9EDFCAFA3DD4E360D4B35DF04A8C8AA3BA6D59F0B347C2DA0225DD790BBBB4F0978E9CBF6ADF62F07147DC487F4B94077B1787495B7C907F431C061893460AB7F2B8B75D14279CF7770FDFCDAFEB223313BB4ECCBB76834B470FFAB120D6DD85D9524D8CD20827625A81473666819E4E14DE0289F22D42EAE21010EBBDD8D88BB0436A1C3EC9A37F97239B9D1999897FE137466E82626614CA8C8D07FF22ADF5DB318D9B47FF25D4295E7F14D987C1A3C8408944D9795726ED0CFB1EB3905DF578A825F0D09167CB30A1BB3256195B6D5A6A0340F9026A14C7D45CE700FFDD0A3C4F00D5A8017D887B7070C3FC115B037F965683D91764354D53EBE70C12AA29135A351AEA77F520C3BFEFAC3FFA04D593F5C4C0000 , N'6.1.3-40302')
Running Seed method.
PM> Update-Database -Verbose
Using StartUp project 'Stats'.
Using NuGet project 'Stats'.
Specify the '-Verbose' flag to view the SQL statements being applied to the target database.
Target database is: 'Stats.DataAccess.StatsDbContext' (DataSource: .\SQLEXPRESS, Provider: System.Data.SqlClient, Origin: Convention).
No pending explicit migrations.
Running Seed method.
PM>
I don't understand why I am not getting an error message if it's not creating a database. Also, am I supposed to have a connectionStrings element in my config files? It's not there. I thought it was automatically created by default.
Tried to redo every step to no avail:
PM> Enable-Migrations
Checking if the context targets an existing database...
Code First Migrations enabled for project Stats.
PM> Add-Migration Initial
Scaffolding migration 'Initial'.
The Designer Code for this migration file includes a snapshot of your current Code First model. This snapshot is used to calculate the changes to your model when you scaffold the next migration. If you make additional changes to your model that you want to include in this migration, then you can re-scaffold it by running 'Add-Migration Initial' again.
A previous migration called 'Initial' was already applied to the target database. If you meant to re-scaffold 'Initial', revert it by running 'Update-Database -TargetMigration 201511280718053_Initial', then delete '201511280832547_Initial.cs' and run 'Add-Migration Initial' again.
PM> Update-Database
Specify the '-Verbose' flag to view the SQL statements being applied to the target database.
Applying explicit migrations: [201511280832547_Initial].
Applying explicit migration: 201511280832547_Initial.
Running Seed method.
PM>
This would normally be a comment, but I'm showing a picture.
If you click on your App_Data folder icon, you will see this icon appear.
Clicking this icon will show/hide certain files in your project.
If there are any files in the folder, they will appear grayed out.
Since your update-database command ran the seed method, it means that the database exists.
Also, you can look in your sql server's data folder or in the physical app's App_Data folder.

MigrateDatabaseToLatestVersion seed() doesn't create tables in database [duplicate]

In my application I enable Code First Migrations with some migrations, Also I use SQL Server Compact for integration test.
When I run my tests, Entity Framework create an empty database and tries to run migration on that empty database and thrown The specified table does not exist.
Based on this report I think usage of Migration in Entity Framework 6 has changed.
I test all Database Initializer with Context.Database.Create(); but in all case tabale's never created.
I don't know that this is EntityFramework's bug or not, but when I made rename the namespace of Migration Configuration class from default (Projectname/Migrations) to any none default name, migration works well.
Context.Database.Create() will not execute migrations! It only creates empty db. To Update database from code to latest version you need to use DbMigrator.Update method:
var migrator = new DbMigrator(new MyMigrationsConfiguration());
migrator.Update();
Alternatively you might use MigrateDatabaseToLatestVersion
Database.SetInitializer(new MigrateDatabaseToLatestVersion<BlogContext, Configuration>());
It is described in details here: http://msdn.microsoft.com/en-us/data/jj591621.aspx#initializer
In case someone still struggles to fix the issue.
The code that follows works for me: add-migration MyFirstMigration
Meanwhile add-migration "MyFirstMigration" with the migration name ramped in quote doesn't work.
There may be previous migration files which the ide may be referring to mostly likely due to caching.
Drop backup and drop target database if it exists, and drop the migration folder.
Now add the migration and you will be good to go.
It does happens when adding model and running add-migration command.
Here is the simplest cause of this issue:
Add a newly added model property into IdentityDbContex class.
Here are the steps:
create model
add property into IdentityDbContex class
run add-migration
update-database

Drop or Recreate database with Entity Framework Migrations (Code-First)

Which is the command to recreate or drop the database when using Entity Framework Migrations, not Initializers?
What should I write on the package manager console?
COMMENT:
I'm looking for some command that gives me the same functionality as Database.SetInitializer<>(new DropCreateDatabaseIfModelChanges<>()); but with the migrations approach.
You can get the same behavior with Migrations by using automatic migrations.
PM> enable-migrations -EnableAutomaticMigrations
In Configuration.cs in the constructor, make sure automatic migrations and allow data loss are set to true...
public Configuration()
{
AutomaticMigrationsEnabled = true;
AutomaticMigrationDataLossAllowed = true;
}
Now whenever your model changes, just execute update-database...
PM> update-database
The schema will be changed to match the models and any existing data in the tables will stay there (unless it's in a renamed or removed column). The Seed method is run after the database is updated so you can further control any changes to the data in there.
I went into server explorer and manually deleted all the tables. Then went to the project\Migrations folder and deleted all the migration scripts.
Then a plain old Update-Database -Force did what I needed.
In VS2015, I did the following to resolve it: In solution explorer menu-->Show All-->The App_Data folder shows the LocalDb mdf file-->Right click the file and click Delete-->In Package Manage Condsole, run: Update-Database -Force

How to delete and recreate from scratch an existing EF Code First database

I am using EF Code First with EF 5 in VS 2012. I use PM update-database command and I have a simple seed method to fill some tables with sample data.
I would like to delete and recreate my x.mdb. The update history seems to be out of sync. If I comment out all my DBSets in my context, update-database runs with no error but leaves some tables in the DB. As I have no valuable data in the DB it seems to the simplest to reset the all thing.
How can I accomplish this?
If I'm understanding it right...
If you want to start clean:
1) Manually delete your DB - wherever it is (I'm assuming you have your connection sorted), or empty it, but easier/safer is to delete it all together - as there is system __MigrationHistory table - you need that removed too.
2) Remove all migration files - which are under Migrations - and named like numbers etc. - remove them all,
3) Rebuild your project containing migrations (and the rest) - and make sure your project is set up (configuration) to build automatically (that sometimes may cause problems - but not likely for you),
4) Run Add-Migration Initial again - then Update-Database
If you worked the correct way to create your migrations by using the command Add-Migration "Name_Of_Migration" then you can do the following to get a clean start (reset, with loss of data, of course):
Update-database -TargetMigration:0
Normally your DB is empty now since the down methods were executed.
Update-database
This will recreate your DB to your current migration
For EntityFrameworkCore you can use the following:
Update-Database -Migration 0
This will remove all migrations from the database.
Then you can use:
Remove-Migration
To remove your migration.
Finally you can recreate your migration and apply it to the database.
Add-Migration Initialize
Update-Database
Tested on EFCore v2.1.0
Similarly for the dotnet ef CLI tool:
dotnet ef database update 0 [ --context dbcontextname ]
dotnet ef migrations add Initialize
dotnet ef database update
Single Liner to Drop, Create and Seed from Package Manager Console:
update-database -TargetMigration:0 | update-database -force
Kaboom.
How about ..
static void Main(string[] args)
{
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<ExampleContext>());
// C
// o
// d
// i
// n
// g
}
I picked this up from Programming Entity Framework: Code First, Pg 28 First Edition.
dbctx.Database.EnsureDeleted();
dbctx.Database.EnsureCreated();
I am using .net Core 6 and this code is directly stripped out of the Program.cs
using Microsoft.EntityFrameworkCore;
namespace RandomProjectName
{
public class Program
{
public static async Task<int> Main(string[] args)
{
var connectionString = "Server=YourServerName;Database=YourDatabaseName;Integrated Security=True;";
var optionsBuilder = new DbContextOptionsBuilder<YourDataContext>();
optionsBuilder.UseSqlServer(connectionString);
var db = new YourDataContext(optionsBuilder.Options);
db.Database.EnsureDeleted();
db.Database.Migrate();
}
}
}
You should have at minimum initial migration for this to work.
There re many ways to drop a database or update existing database, simply you can switched to previous migrations.
dotnet ef database update previousMigraionName
But some databases have limitations like not allow to modify after create relationships, means you have not allow privileges to drop columns from ef core database providers but most of time in ef core drop database is allowed.so you can drop DB using drop command
and then you use previous migration again.
dotnet ef database drop
PMC command
PM> drop-database
OR you can do manually deleting database and do a migration.
If you created your database following this tutorial: https://msdn.microsoft.com/en-au/data/jj193542.aspx
... then this might work:
Delete all .mdf and .ldf files in your project directory
Go to View / SQL Server Object Explorer and delete the database from the (localdb)\v11.0 subnode. See also https://stackoverflow.com/a/15832184/2279059
Using EF6 with ASP.Net Core 5 I found these commands handy during first initialization of the database:
Remove-Migration -force; Add-Migration InitialMigration; Update-Database;
It removes the last migration (should be the only one), creates it again, then refreshes the database. You can thus type these three commands in one line into the Package Management Console after editing your DbContext and it'll update InitialMigration and database.
A little annoying is that it'll compile your project three times in a row but a least no further manual steps (like deleting the migration files) are necessary.
When you remove an entity you'll need to issue Remove-Database before updating. So the line becomes:
Remove-Migration -force; Add-Migration InitialMigration; Remove-Database; Update-Database;
Problematic here: You need to confirm removing the database + 4 rebuilds.
Take these steps:
Delete those object which should be deleted from the context // Dbset<Item> Items{get;set;}
and in Nuget Console run these commands
add-migration [contextName]
update-database -verbose
It will drop table(s) that not exist in Context, but already created in database
Let me help in updating the answers here since new users will find it useful.
I believe the aim is to delete the database itself and recreate it using EF Code First approach.
1.Open your project in Visual Studio using the ".sln" extention.
2.Select Server Explorer( it is oftentimes on the left)
3.Select SQL Server Object Explorer.
4.The database you want to delete would be listed under any of the localDB. Right-Click it and select delete.
Since this question is gonna be clicked some day by new EF Core users and I find the top answers somewhat unnecessarily destructive, I will show you a way to start "fresh". Beware, this deletes all of your data.
Delete all tables on your MS SQL server. Also delete the __EFMigrations table.
Type dotnet ef database update
EF Core will now recreate the database from zero up until your latest migration.

Resources