Ehsan Ghanbari

Experience, DotNet, Solutions

Using entity framework Code First migration

While using Entity Framework, definitely you will need to migrate your database! In SQL server, you need to write a query to do that. Entity framework is doing the same task but in your application via C# code. Create a simple console application and install entity framework on it and C# class with the following properties:

 

 public class ClassRoom

    {

        public int Id { get; set; }

        public string Title { get; set; }

        public DateTime BeginDate { get; set; }

    }

 

Map the above class via EntityFramework:

 

class ClassRoomMapping : EntityTypeConfiguration<ClassRoom>
    {
        public ClassRoomMapping()
        {
            ToTable("ClassRoom", "MySchema");
            Property(c => c.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
            Property(c => c.Title).HasColumnType(SqlDbType.NVarChar.ToString()).HasMaxLength(200);
            Property(c => c.BeginDate).HasColumnType(SqlDbType.DateTime.ToString());
        }
    }

 

Now let's create our Context Class:

 

 class OurContextClass : DbContext
    {
        public OurContextClass() : base("SampleConnection")
        {
          
        }

        public DbSet<ClassRoom> ClassRooms { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Configurations.Add(new ClassRoomMapping());
            base.OnModelCreating(modelBuilder);
        }
    }

 

 

As you see, we created a property to access the ClassRoom object via DbSet and we defined the ClassRoomMapping in modelBuilder configuration to let entity framework read from our custom mapping. Now add connection string into the app.config file: 

 

 <connectionStrings>
    <add name="SampleConnection" connectionString="Data Source=DESKTOP-VIsdsJ30;Initial Catalog=SampleDataBase;Integrated Security=True" providerName="System.Data.SqlClient"/>
  </connectionStrings>

 

Now in the Main method call the ClassRoom to create the database in SQL server:

 

 static void Main(string[] args)

        {

            OurContextClass occ = new OurContextClass();

            occ.ClassRooms.Add(new ClassRoom { Id = 1, Title = "First One", BeginDate = DateTime.Now });

            occ.SaveChanges();

        }

 

By running the application the DataBase will be created and you will have a table and two table:

  1. ClassRoom
  2. __MigrationHistory

The second table will contain you migration histories. Now For enabling the migration, first you need to execute the following command in Console Package Manager: 

enable-migrations

If you do it successfully, a configuration class will be added inside a folder named Migrations in your project with the following definition:

 

 internal sealed class Configuration : DbMigrationsConfiguration<ConsoleApp1.OurContextClass>
    {
        public Configuration()
        {
            AutomaticMigrationsEnabled = false;
            ContextKey = "ConsoleApp1.OurContextClass";
        }

        protected override void Seed(ConsoleApp1.OurContextClass 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.
        }
    }

 

Now we want to add some extra field too, the new ClassRoom and its mapping would be like this:

 

 public class ClassRoom
    {
        public int Id { get; set; }

        public string Title { get; set; }

        public DateTime BeginDate { get; set; }

        public int ClassNumeber { get; set; }
    }

    class ClassRoomMapping : EntityTypeConfiguration<ClassRoom>
    {
        public ClassRoomMapping()
        {
            ToTable("ClassRoom", "MySchema");
            Property(c => c.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
            Property(c => c.Title).HasColumnType(SqlDbType.NVarChar.ToString()).HasMaxLength(200);
            Property(c => c.BeginDate).HasColumnType(SqlDbType.DateTime.ToString());
            Property(c => c.ClassNumeber).HasColumnType(SqlDbType.Int.ToString()).IsRequired();
        }
    }

 

The ClassNumber is new the field and notices that it's required and we should initialize it while migrating, execute the following command in Console Package Manager:

PM> Add-Migration AddClassNumberField

Add-Migration is the command that adds the Migration class into Migrations folder with the named you to give it:

 

 public partial class AddClassNumberField : DbMigration
    {
        public override void Up()
        {
            AddColumn("MySchema.ClassRoom", "ClassNumeber", c => c.Int(nullable: false, defaultValue: 1));
        }

        public override void Down()
        {
            DropColumn("MySchema.ClassRoom", "ClassNumeber");
        }
    }

 

As you can see I added the defaultValue because it's the required field. And finally, you should run the Update-Database command to update the database with the new field. For summarizing the command we used:

 

 

About Me

Ehsan Ghanbari

Hi! my name is Ehsan. I'm a developer, passionate technologist, and fan of clean code. I'm interested in enterprise and large-scale applications architecture and design patterns and I'm spending a lot of my time on architecture subject. Since 2008, I've been as a developer for companies and organizations and I've been focusing on Microsoft ecosystem all the time. During the&nb Read More

Post Tags
Pending Blog Posts
Strategic design
Factory Pattern
time out pattern in ajax
Selectors in Jquery
Peridic pattern
How to query over Icollection<> of a type with linq
How to use PagedList In asp.net MVC
Using Generic type for type casting in F#
Domain driven design VS model driven architecture
What's the DDD-lite?
comments powered by Disqus