This article is a mirror article of machine translation, please click here to jump to the original article.

View: 27080|Reply: 0

[Source] Update your database with Code First migration

[Copy link]
Posted on 6/7/2018 3:56:58 PM | | |
Code First Migration, you can update your changes to the model in your code to the database, to use Code First Migration, you first need to open it:

In the Tools-NuGet Package Manager-Package Manager console, type: Enable-Migrations -ContextTypeName CodeFirstExistingDB.DataModel.StoreContext, press Enter. (Note that you need to define the context you need to use because the authentication context is automatically created when you create the project.) Once done, a Migrations folder is created, which contains a Configuration.cs class.

At this point, there is an extra step required to make Code First work, if you create a migration now, it will try to add the contextual entity to the database, and the migration will fail because the Products and categories tables already exist in the database. So first we need to create a migration that is initialized to empty, and then we can add a migration to any modifications.

PM> Update-Database
Specify the "-Verbose" flag to view the SQL statements applied to the target database.
No pending explicit migrations.
Applying automatic migration: 201806070740457_AutomaticMigration.
System.Data.SqlClient.SqlException (0x80131904): An object named 'Account' already exists in the database.
   at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action'1 wrapCloseInAction)
   at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action'1 wrapCloseInAction)
   at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
   In System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
   at System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean async, Int32 timeout, Boolean asyncWrite)
   In System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource'1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry)
   In System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
   In System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher. <NonQuery>b__0(DbCommand t, DbCommandInterceptionContext`1 c)
   In System.Data.Entity.Infrastructure.Interception.InternalDispatcher'1.Dispatch[TTarget,TInterceptionContext,TResult](TTarget target, Func'3 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed)
   In System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.NonQuery(DbCommand command, DbCommandInterceptionContext interceptionContext)
   In System.Data.Entity.Internal.InterceptableDbCommand.ExecuteNonQuery()
   In System.Data.Entity.Migrations.DbMigrator.ExecuteSql(MigrationStatement migrationStatement, DbConnection connection, DbTransaction transaction, DbInterceptionContext interceptionContext)
   In System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.ExecuteSql(MigrationStatement migrationStatement, DbConnection connection, DbTransaction transaction , DbInterceptionContext interceptionContext)
   In System.Data.Entity.Migrations.DbMigrator.ExecuteStatementsInternal(IEnumerable'1 migrationStatements, DbConnection connection, DbTransaction transaction, DbInterceptionContext interceptionContext)
   In System.Data.Entity.Migrations.DbMigrator.ExecuteStatementsWithinTransaction(IEnumerable'1 migrationStatements, DbTransaction transaction, DbInterceptionContext interceptionContext)
   In System.Data.Entity.Migrations.DbMigrator.ExecuteStatementsWithinNewTransaction(IEnumerable'1 migrationStatements, DbConnection connection, DbInterceptionContext interceptionContext)
   In System.Data.Entity.Migrations.DbMigrator.ExecuteStatementsInternal(IEnumerable'1 migrationStatements, DbConnection connection, DbInterceptionContext interceptionContext)
   at System.Data.Entity.Migrations.DbMigrator.ExecuteStatementsInternal(IEnumerable'1 migrationStatements, DbConnection connection)
   at System.Data.Entity.Migrations.DbMigrator.<>c__DisplayClass32. <ExecuteStatements>b__30()
   In System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.<>c__DisplayClass1. <Execute>b__0()
   at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func'1 operation)
   In System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Action operation)
   In System.Data.Entity.Migrations.DbMigrator.ExecuteStatements(IEnumerable'1 migrationStatements, DbTransaction existingTransaction)
   In System.Data.Entity.Migrations.DbMigrator.ExecuteStatements(IEnumerable'1 migrationStatements)
   at System.Data.Entity.Migrations.Infrastructure.MigratorBase.ExecuteStatements(IEnumerable'1 migrationStatements)
   In System.Data.Entity.Migrations.DbMigrator.ExecuteOperations(String migrationId, VersionedModel targetModel, IEnumerable'1 operations, IEnumerable'1 systemOperations, Boolean downgrading, Boolean auto)
   at System.Data.Entity.Migrations.DbMigrator.AutoMigrate(String migrationId, VersionedModel sourceModel, VersionedModel targetModel, Boolean downgrading)
   In System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.AutoMigrate(String migrationId, VersionedModel sourceModel, VersionedModel targetModel, Boolean downgrading)
   at System.Data.Entity.Migrations.DbMigrator.Upgrade(IEnumerable'1 pendingMigrations, String targetMigrationId, String lastMigrationId)
   at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.Upgrade(IEnumerable'1 pendingMigrations, String targetMigrationId, String lastMigrationId)
   at System.Data.Entity.Migrations.DbMigrator.UpdateInternal(String targetMigration)
   In System.Data.Entity.Migrations.DbMigrator.<>c__DisplayClasse. <Update>b__d()
   at System.Data.Entity.Migrations.DbMigrator.EnsureDatabaseExists(Action mustSucceedToKeepDatabase)
   at System.Data.Entity.Migrations.Infrastructure.MigratorBase.EnsureDatabaseExists(Action mustSucceedToKeepDatabase)
   at System.Data.Entity.Migrations.DbMigrator.Update(String targetMigration)
   In System.Data.Entity.Migrations.Infrastructure.MigratorBase.Update(String targetMigration)
   at System.Data.Entity.Migrations.Design.ToolingFacade.UpdateRunner.RunCore()
   In System.Data.Entity.Migrations.Design.ToolingFacade.BaseRunner.Run()
ClientConnectionId:dcf676a8-d2b3-4232-89dd-35e15fb8160d
Error Number:2714,State:6,Class:16
An object named 'Account' already exists in the database.

If you encounter the above error, type Add-Migration InitialCreate -IgnoreChanges in the Package Manager console to create an empty migration.

The IgnoreChanges logo is used to ensure that nothing is done for this migration. Doing it creates a migrations table in the database, which is a snapshot of the database before it is migrated.

Next, enter update-database in the package manager console to update the initialization migration to the database.

After the migration is initialized, update the database using Code First Migration:

Add the Descrip{filter}tion column to the Product table and set the length to 50, ([StringLength(50)]); Now add a new migration to update the changes to the database.

In the Package Manager console, enter:Add-Migration add_product_descrip{filter}tion, (add_product_descrip{filter}tion) will add a file to the Migrations folder to describe the migration. Next, in the Package Manager console, type:

update-database, the new column will be added to the Products table.





Previous:TCP port communication connection demo
Next:asp.net mvc uses the RenderAction local view to load dynamic data
Disclaimer:
All software, programming materials or articles published by Code Farmer Network are only for learning and research purposes; The above content shall not be used for commercial or illegal purposes, otherwise, users shall bear all consequences. The information on this site comes from the Internet, and copyright disputes have nothing to do with this site. You must completely delete the above content from your computer within 24 hours of downloading. If you like the program, please support genuine software, purchase registration, and get better genuine services. If there is any infringement, please contact us by email.

Mail To:help@itsvse.com