Entity Framework code-first: Automated Migration

Source: Internet
Author: User

Automated Migration:

The Entity framework 4.3 has introduced automated migration so, you don't have to process database migration manually in T He code file, for each of the change your domain classes. You just need to run a command on package Manger Console to accomplish this.

Let's see how you can use the automated migration.

As you know, you don't have a database when you start writing your Code-first application. For example, we start writing a application with Student and Course entity classes. Before running the application, which does not has its database created yet, and you have to enable automated migration by RU Nning the ' enable-migrations ' command in the package Manager Console, as shown below:

First, open the Package Manager console from Tools→library Package Manager→package Manager console and then run "enabl E-migrations–enableautomaticmigration: $true "command (make sure, the default project is the project where your Contex T class is)

Once The command runs successfully, it creates an internal sealed Configuration class in the Migration folder in your Proj Ect:

If you open this and see the class shown below, then you'll find automaticmigrationsenabled = True in the constructor.

Internal Sealed classConfiguration:dbmigrationsconfiguration<schooldatalayer.schooldbcontext>    {         PublicConfiguration () {automaticmigrationsenabled=true; }        protected Override voidSeed (Schooldatalayer.schooldbcontext context) {//This method is called after migrating to the latest version. //You can use the dbset<t>. AddOrUpdate () Helper extension method//To avoid creating duplicate seed data.            e.g. //            //context. People.addorupdate (//p = p.fullname,//new Person {FullName = "Andrew Peters"},//new Person {FullName = "Brice Lambson"},//new Person {FullName = "Rowan Miller"}//    ); //        }    }

You also need to set the database initializer in the context class with the new DB initialization strategy migratedatabase Tolatestversion, as shown below:

 Public classSchooldbcontext:dbcontext { PublicSchooldbcontext ():Base("schooldbconnectionstring") {Database.setinitializer (NewMigratedatabasetolatestversion<schooldbcontext, Schooldatalayer.migrations.configuration> ("schooldbconnectionstring")); }     PublicDbset<student> Students {Get;Set; }  PublicDbset<course> Courses {Get;Set; } protected Override voidonmodelcreating (Dbmodelbuilder modelBuilder) {Base.    Onmodelcreating (ModelBuilder); }}

As you can see in the code shown above, we have passed the Configuration class name, which is created by command, along W ITH the context class name.

Now is set for automated migration. It'll automatically take care of migration and when you change the model. Run the application and look at the created database:

You'll find that it had created one system table __migrationhistory along with other tables. This is a where automated migration maintains the history of the database changes.

Now let's add a standard entity class. Run the application again and you'll see that it had automatically created a standard table.

Wait a minute, this works if you add a new entity class or the Remove an entity class, and what's about adding or removing prope Rties from the entity class? To try this, let's remove the Description property from standard class and run the application.

Oops. An error message would appear:

This was because you would lose data in Description column, if you remove it from the standard class. So to handle this kind of scenario, you have to set automaticmigrationdatalossallowed = True in the Configuration Class co Nstructor, along with automaticmigrationsenabled = True.

Note: You can find more information about parameters so we can pass to the enable-migrations command using the "Get-help enabl E-migrations "command. For more detailed help use "Get-help enable-migrations–detailed"

Thus, migration can be handled automatically.

Entity Framework code-first: Automated Migration

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.