ASP.NET MVC4 新手入门教程特别篇之一----Code First Migrations更新数据库结构(数据迁移)修改Entity FrameWork 数据结构(不删除数据)

背景

code first起初当修改model后,要持久化至数据库中时,总要把原数据库给删除掉再创建(DropCreateDatabaseIfModelChanges),此时就会产生一个问题,当我们的旧数据库中包含一些测试数据时,当持久化更新后,原数据将全部丢失,故我们可以引入EF的数据迁移功能来完成。

 

要求

 

  1. 已安装NuGet

 

过程示例

 

 

原model
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;

namespace MvcApplication1.Models
{
    public class Movie
    {
        public int ID { get; set; }
        public string Title { get; set; }
        public DateTime ReleaseDate { get; set; }
        public string Genre { get; set; }
        public decimal Price { get; set; }

        public string Rating { get; set; }
    }
    public class MovieDBContext : DbContext
    {
        public DbSet<Movie> Movies { get; set; }
    }
}

 


 

//新model  
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;

namespace MvcApplication1.Models
{
    public class Movie
    {
        public int ID { get; set; }
        public string Title { get; set; }
        public DateTime ReleaseDate { get; set; }
        public string Genre { get; set; }
        public decimal Price { get; set; }
        public decimal VipPrice { get; set; }

        public string Rating { get; set; }
    }
    public class MovieDBContext : DbContext
    {
        public DbSet<Movie> Movies { get; set; }
    }
}

 

注:区别在于,我们给Movie新加了一个VipPrice属性。

 

接下来,我们将开始持久化此model至数据库中(我们现在对数据库表结构进行修改,增加一个VipPrice 字段)

 

1:在config中配置数据库连接:

 

  <connectionStrings>
    <add name="MovieDBContext" connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Movies.mdf;Integrated Security=True" providerName="System.Data.SqlClient" />
   </connectionStrings>

 


 

 

2:打开NuGet控制台:

 

 

 

3:运行命令Enable-Migrations

可能会出现如下错误:

PM> Enable-Migrations
More than one context type was found in the assembly 'MvcApplication1'.
To enable migrations for MvcApplication1.Models.UsersContext, use Enable-Migrations -ContextTypeName MvcApplication1.Models.UsersContext.
To enable migrations for MvcApplication1.Models.MovieDBContext, use Enable-Migrations -ContextTypeName MvcApplication1.Models.MovieDBContext.
To enable migrations for MvcApplication1.PurchaseRequestEntities, use Enable-Migrations -ContextTypeName MvcApplication1.PurchaseRequestEntities.

这是因为我之前 执行过 Enable-Migrations ,系统提示我已经存在MvcApplication1 context 

此时项目会出现如下文件夹:

 

打开configuation.cs,将作出如下修改:

 

   public Configuration()
        {
            AutomaticMigrationsEnabled = true;
        }

 

4:再次执行Update-Database

 

如下:

PM> Update-Database
指定“-Verbose”标记以查看应用于目标数据库的 SQL 语句。
无任何待定的基于代码的迁移。
正在应用自动迁移: 201501220847062_AutomaticMigration。
正在运行 Seed 方法。

 

如果确保没事,只需给此命令加个强制执行的参数即可:

Enable-Migrations -Force

最后再次执行:Update-Database

数据库中已经增加VipPrice字段

数据库中的原数据也没有丢失!

 

posted @ 2015-01-23 09:19  178mz  阅读(680)  评论(0编辑  收藏  举报