asp.net-mvcasp.net-mvc-4code-migration

MVC update model with Code-Migrations


I am making my project in MVC4, where i am using my Code first approach. i need to update my model

i have a following property which needs to be update , how can i achieve this

public class ContactForm
    {
        public char Phone { get; set; }
    }

    public class ConContext : DbContext
    {
        public DbSet<ContactForm> ContactForms { get; set; }
    }
}

i want to update Phone propery to

public char Phone { get; set; }

thnx in advance, i have installed migrations to my projet already

My configuration.cs

namespace MyCRM.Migrations
{
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Migrations;
    using System.Linq;

    internal sealed class Configuration : DbMigrationsConfiguration<MyCRM.Models.ConContext>
    {
        public Configuration()
        {
            AutomaticMigrationsEnabled = false;
        }

        protected override void Seed(MyCRM.Models.ConContext 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" }
            //    );
            //
        }
    }
}

Solution

  • The normal flow with EF code-first is too first update the model (a C# file) :

    public class ContactForm
    {
        public string Phone { get; set; } //previously, this was let's say of type int
    }
    

    Then, you build your project and after that in the Package Manager Console, you have to call Add-Migration with some label (in order to rollback changes later if needed) :

    Add-Migration Phone
    

    This will add to your solution a file named like this 201409xxxxxxxx_Phone under the directory Migrations.

    Then you have to put the changes to your database which can be done with the command (always in the console) :

    Update-Database
    

    Then, you should be done : the property Phone is of type string everywhere.