MVC Code First 当实体类发生变化时,如何自动更新数据库表
下面做一个例子,Category是用户新建的一个实体类,然后添加一个字段,然后让数据库中的Category表也添加一个字段
1.Category.cs
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; namespace BlogAppDAL.Entities { public class Category { public int Id { get; set; } [Required] [StringLength(200)] public string CategoryName { get; set; } //public DateTime CreateDate { get; set; } public virtual ICollection<Blog> Blogs { get; set; } public Category() { Blogs = new HashSet<Blog>(); } } }
开始了添加一个字段,代码如下:
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; namespace BlogAppDAL.Entities { public class Category { public int Id { get; set; } [Required] [StringLength(200)] public string CategoryName { get; set; } public DateTime CreateDate { get; set; } public virtual ICollection<Blog> Blogs { get; set; } public Category() { Blogs = new HashSet<Blog>(); } } }
在上下文当中写入下面的代码:
代码如下:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.Entity; using BlogAppDAL.Entities; using System.Data.Entity.ModelConfiguration.Conventions; using System.Data.Entity.Migrations; using System.Data.Entity.Infrastructure; namespace BlogAppDAL { public class BlogAppContext : DbContext { public BlogAppContext() : base("name=BlogAppConn") { //自动创建表,如果Entity有改到就更新到表结构 Database.SetInitializer<BlogAppContext>(new MigrateDatabaseToLatestVersion<BlogAppContext, ReportingDbMigrationsConfiguration>()); } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Conventions.Remove<PluralizingTableNameConvention>(); //表名为类名,不是带s的表名 //移除复数表名的契约 } internal sealed class ReportingDbMigrationsConfiguration : DbMigrationsConfiguration<BlogAppContext> { public ReportingDbMigrationsConfiguration() { AutomaticMigrationsEnabled = true;//任何Model Class的修改將會直接更新DB AutomaticMigrationDataLossAllowed = true; } } public virtual DbSet<Blog> Blogs { get; set; } public virtual DbSet<Category> Categories { get; set; } public virtual DbSet<Comment> Comments { get; set; } public virtual DbSet<Role> Roles { get; set; } public virtual DbSet<User> Users { get; set; } } }
然后运行下程序就更新了数据库中的表了。而且连Migrations文件夹都不需要了
(本人微信号:Liberty-bcy)如果,你正在埋怨命运不眷顾,那请记住:命,是失败者的借口;运,是成功者的谦词。