Entity Framework Code-First(21):Automated Migration

Automated Migration:

Entity framework 4.3 has introduced Automated Migration so that you don‘t have to process database migration manually in the code file, for each change you make in your domain classes. You just need to run a command in 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 an application with Student and Course entity classes. Before running the application, which does not have its database created yet, you have to enable automated migration by running the ‘enable-migrations‘ command in Package Manager Console, as shown below:

First, open the package manager console from Tools → Library Package Manager → Package Manager Console and then run "enable-migrations –EnableAutomaticMigration:$true" command (make sure that the default project is the project where your context class is)

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

If you open this and see the class shown below, then you will find AutomaticMigrationsEnabled = true in the constructor.

internal sealed class Configuration : DbMigrationsConfiguration<SchoolDataLayer.SchoolDBContext>
    {
        public Configuration()
        {
            AutomaticMigrationsEnabled = true;
        }

        protected override void Seed(SchoolDataLayer.SchoolDBContext context)
        {
            //  This method will be 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 MigrateDatabaseToLatestVersion, as shown below:

public class SchoolDBContext: DbContext
{
    public SchoolDBContext(): base("SchoolDBConnectionString")
    {
        Database.SetInitializer(new MigrateDatabaseToLatestVersion<SchoolDBContext, SchoolDataLayer.Migrations.Configuration>("SchoolDBConnectionString"));

    }

    public DbSet<Student> Students { get; set; }
    public DbSet<Course> Courses { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {

        base.OnModelCreating(modelBuilder);
    }

}

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

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

You will find that it has created one system table __MigrationHistory along with other tables. This is where automated migration maintains the history of database changes.

Now let‘s add a Standard entity class. Run the application again and you will see that it has automatically created a Standard table.

Wait a minute, this works if you add a new entity class or remove an entity class, but what about adding or removing properties from the entity class? To try that, let‘s remove the Description property from Standard class and run the application.

Oops…. an error message will appear:

This is because you will 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 constructor, along with AutomaticMigrationsEnabled = true.

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

Thus, migration can be handled automatically.

时间: 2024-10-30 17:46:17

Entity Framework Code-First(21):Automated Migration的相关文章

Entity Framework Code First (三)Data Annotations

Entity Framework Code First 利用一种被称为约定(Conventions)优于配置(Configuration)的编程模式允许你使用自己的 domain classes 来表示 EF 所依赖的模型去执行查询.更改追踪.以及更新功能,这意味着你的 domain classes 必须遵循 EF 所使用的约定.然而,如果你的 domain classes 不能遵循 EF 所使用的约定,此时你就需要有能力去增加一些配置使得你的 classes 能够满足 EF 所需要的信息. C

Entity Framework Code First (二)Custom Conventions

------------------------------------------------------------------------------------------------------------ 注意:以下所讨论的功能或 API 等只针对 Entity Framework 6 ,如果你使用早期版本,可能部分或全部功能不起作用! --------------------------------------------------------------------------

Entity Framework Code First (一)Conventions

Entity Framework 简言之就是一个ORM(Object-Relational Mapper)框架. Code First 使得你能够通过C#的类来描述一个模型,模型如何被发现/检测就是通过一些约定(Conventions).Conventions 就是一系列规则的集合,被用于对基于类别定义的概念模型的自动装配. 这些约定都被定义于 System.Data.Entity.ModelConfiguration.Conventions 命名空间下. 当然你可以进一步地对你的模型作出配置,

Entity Framework Code First (四)Fluent API - 配置属性/类型

小分享:我有几张阿里云优惠券,用券购买或者升级阿里云相应产品最多可以优惠五折!领券地址:https://promotion.aliyun.com/ntms/act/ambassador/sharetouser.html?userCode=ohmepe03 上篇博文说过当我们定义的类不能遵循约定(Conventions)的时候,Code First 提供了两种方式来配置你的类:DataAnnotations 和 Fluent API, 本文将关注 Fluent API.  一般来说我们访问 Flu

Entity Framework Code First (八)迁移 Migrations

参考页面: http://www.yuanjiaocheng.net/entity/Persistence-in-EF.html http://www.yuanjiaocheng.net/entity/crud-in-connected.html http://www.yuanjiaocheng.net/entity/crud-in-Disconnected.html http://www.yuanjiaocheng.net/entity/add-entity-in-disconnected.h

Entity Framework Code First (五)Fluent API - 配置关系

上一篇文章我们讲解了如何用 Fluent API 来配置/映射属性和类型,本文将把重点放在其是如何配置关系的. 文中所使用代码如下 public class Student { public int ID { get; set; } public string Name { get; set; } public DateTime EnrollmentDate { get; set; } // Navigation properties public virtual Address Address

Entity Framework Tutorial Basics(2):What is Entity Framework?

What is Entity Framework? Writing and managing ADO.Net code for data access is a tedious and monotonous job. Microsoft has provided an O/RM framework called "Entity Framework" to automate database related activities for your application. Microso

Entity Framework Tutorial Basics(1):Introduction

以下系列文章为Entity Framework Turial Basics系列 http://www.entityframeworktutorial.net/EntityFramework5/entity-framework5-introduction.aspx ----------------------------------------------------------------------------------------------------------------------

Entity Framework Tutorial Basics(37):Lazy Loading

Lazy Loading: One of the important functions of Entity Framework is lazy loading. Lazy loading means delaying the loading of related data, until you specifically request for it. For example, Student class contains StudentAddress as a complex property