The Code First Migrations feature solves this problem by enabling Code First to update the database schema instead of dropping and re-creating the database. In this tutorial, you'll deploy the application, and to prepare for that you'll enable Migrations.
- Disable the initializer that you set up earlier by commenting out or deleting the
contexts
element that you added to the application Web.config file.XML<entityFramework> <!--<contexts> <context type="ContosoUniversity.DAL.SchoolContext, ContosoUniversity"> <databaseInitializer type="ContosoUniversity.DAL.SchoolInitializer, ContosoUniversity" /> </context> </contexts>--> <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework"> <parameters> <parameter value="v11.0" /> </parameters> </defaultConnectionFactory> <providers> <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" /> </providers> </entityFramework>
- Also in the application Web.config file, change the name of the database in the connection string to ContosoUniversity2.XML
<connectionStrings> <add name="SchoolContext" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=ContosoUniversity2;Integrated Security=SSPI;" providerName="System.Data.SqlClient" /> </connectionStrings>
This change sets up the project so that the first migration creates a new database. This isn't required but you'll see later why it's a good idea. - From the Tools menu, select NuGet Package Manager > Package Manager Console.
- At the
PM>
prompt enter the following commands:textenable-migrations add-migration InitialCreate
Theenable-migrations
command creates a Migrations folder in the ContosoUniversity project, and it puts in that folder a Configuration.cs file that you can edit to configure Migrations.(If you missed the step above that directs you to change the database name, Migrations will find the existing database and automatically do theadd-migration
command. That's okay, it just means you won't run a test of the migrations code before you deploy the database. Later when you run theupdate-database
command nothing will happen because the database already exists.)
No comments:
Post a Comment