Thursday 16 July 2015

Add Migrations to existing code first Model

Following steps guides you how to generate migration code for the existing code first dbContext model.

1. Create your model class
 public class NewsSlider
    {
        [Key]
        [HiddenInput(DisplayValue = false)]
        public int NewsSliderId { get; set; }

        [Display(Name = "News Item")]
        [StringLength(500)]
        public string NewsItem { get; set; }
    }


2. Update your dbContext class as follows
 
   public System.Data.Entity.DbSet<myapp .models.newsslider=""> NewsSliders { get; set; }

3. Execute Add-Migration NewsSlider in the Package Manager console

4. This would generate the migration code using scaffolding.
  public partial class NewsSlider : DbMigration
    {
        public override void Up()
        {
            CreateTable(
                "dbo.NewsSliders",
                c => new
                    {
                        NewsSliderId = c.Int(nullable: false, identity: true),
                        NewsItem = c.String(maxLength: 500),
                    })
                .PrimaryKey(t => t.NewsSliderId);
            
        }
        
        public override void Down()
        {
            DropTable("dbo.NewsSliders");
        }
    }

No comments:

Post a Comment