Code first, DB update

来源:互联网 发布:淘宝买家两钻有什么用 编辑:程序博客网 时间:2024/06/05 08:34

1, change code in model, add/delete new field to table, update db.

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Data.Entity;using System.ComponentModel.DataAnnotations;namespace MvcMovie.Models{    public class Movie    {        public int ID { get; set; }        [Required]        public string Title { get; set; }        [DataType(DataType.Date)]        public DateTime ReleaseDate { get; set; }        [Required]        [StringLength(5)]        public string Genre { get; set; }        [Range(1,100)]        public decimal Price { get; set; }        [Required]        public int rate { get; set; }        public string test { get; set; }   // add new field or delete this field    }    public class MovieDBContext : DbContext    {        public DbSet<Movie> Movies { get; set; }    }}


2, tool -> library manager -> package manager console.

run command:   Enable-Migrations -ContextTypeName MvcMovie.Models.MovieDBContext  (your model namespace.DBcontextClass)

  1. this command will create folder Migrations and configuration.cs in it
  2. only need run once (if you don't have  folder Migrations or the folder Migrations has been deleted)
  3. if you have folder Migrations and configruation.cs in it. go to next step.
3. in package manager console. 
run command:  add-migration AddDataAnnotationsMig 
  • this command will detect the change you made and generate code to change the db.
  • example:       Migrations/201302041554137_AddDataAnnotationsMig3.cs
4. run command:  
run command: update-database



原创粉丝点击