1. 程式人生 > >程式碼生成資料庫及更新資料庫:Entity Framework first code(http://www.cnblogs.com/haogj/archive/2012/02/17/2356537.ht

程式碼生成資料庫及更新資料庫:Entity Framework first code(http://www.cnblogs.com/haogj/archive/2012/02/17/2356537.ht

準備工作

在開始之前,我們需要一個專案,以及一個 Code First 的模型,對於這次演示,我們使用典型的部落格 Blog 和回覆 Post 模型。

1. 建立新的  MigrationsCodeDemo 控制檯應用程式


2. 為專案新增最新版本的 EntityFramework NuGet 包。

找到包管理器控制檯。


執行 Install-Package EntityFramework 命令。


成功之後的專案檔案如下:


建立初始的模型和資料庫

1. 增加如下的 Model.cs 檔案,程式碼定義了一個單個的 Blog 類表示我們的模型物件,BlogContext 類就是 EF Code First 的上下文。

using System.Data.Entity;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity.Infrastructure;

namespace MigrationsCodeDemo
{
    publicclass BlogContext : DbContext
    {
        public DbSet<Blog> Blogs { get; set; }
    }

    public
class Blog { publicint BlogId { get; set; } publicstring Name { get; set; } } }

2. 現在我們已經有了一個模型,是時候進行一次資料訪問了。使用如下的程式碼更新 Program.cs 檔案。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MigrationsCodeDemo
{
    class
Program { staticvoid Main(string[] args) { using (var db = new BlogContext()) { db.Blogs.Add(new Blog { Name = "Another Blog " }); db.SaveChanges(); foreach (var blog in db.Blogs) { Console.WriteLine(blog.Name); } } } } }
3. 執行程式,現在就可以在你本地的 SQLExpress 資料庫中看到資料庫了。


啟用遷移

1. 在 Blog 類中增加一個 Url 屬性。

    public class Blog
    {
        public int BlogId { get; set; }
        public string Name { get; set; }
        public string Url { get; set; }
    }

2. 現在執行程式,會看到如下的異常。
未經處理的異常:  System.InvalidOperationException: The model backing the 'BlogContext' context has changed since the database was created. Consider using Code First Migrations to update the database (http://go.microsoft.com/fwlink/?LinkId=238269).

3. 正如異常建議,現在是開始使用 Code First 遷移的時候了,第一步是為我們的上下文啟用遷移支援。

   在包管理器的控制檯中執行命令:Enable-Migrations


4. 這個命令在專案中增加名為 Migrations 資料夾,資料夾中包含兩個檔案。


Configuration 類,這個類允許你配置你的上下文的遷移行為,在這個演示中,我們僅僅使用預設配置。

因為在這個專案中只有一個上下文,Enable-Migrations 自動填充應用的這個上下文。

201202171353373_InitialCreate.cs 中的 InitialCreate ,生成這個遷移是因為我們已經通過 Code First 建立了一個數據庫。這個遷移中的程式碼表示我們已經建立的資料庫,

namespace MigrationsCodeDemo.Migrations
{
    using System.Data.Entity.Migrations;
    
    publicpartialclass InitialCreate : DbMigration
    {
        publicoverridevoid Up()
        {
            CreateTable(
                "Blogs",
                c => new
                    {
                        BlogId = c.Int(nullable: false, identity: true),
                        Name = c.String(),
                    })
                .PrimaryKey(t => t.BlogId);
            
        }
        
        publicoverridevoid Down()
        {
            DropTable("Blogs");
        }
    }
}

第一個遷移

你會使用到兩個命令

Add-Migration,將會基於你對模型的修改建立一個遷移的腳手架。

Update-Database,將沒有提交的修改提交到資料庫。

1. 我們首先為我們新增加的 Url 屬性建立一個遷移,Add-Migration 會幫我們完成這個工作,我們為這個遷移命名為:AddBlogUrl。

 執行:Add-Migration AddBlogUrl


專案中增加了一個檔案 201202171413369_AddBlogUrl.cs


內容如下:

namespace MigrationsCodeDemo.Migrations
{
    using System.Data.Entity.Migrations;
    
    publicpartialclass AddBlogUrl : DbMigration
    {
        publicoverridevoid Up()
        {
            AddColumn("Blogs", "Url", c => c.String());
        }
        
        publicoverridevoid Down()
        {
            DropColumn("Blogs", "Url");
        }
    }
}

3. 我們可以在這個遷移中編輯或者增加內容,但是現在看起來就很不錯,讓我們將這個遷移提交到資料庫中。

執行: Update-Database


4. 現在的資料庫中已經包含了 Url 列。


定製遷移

下面我們看看如何定製遷移。

1. 在程式碼中增加一個回覆的類 Post,同時在 Blog 中增加一個評分屬性。

using System.Data.Entity;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity.Infrastructure;

namespace MigrationsCodeDemo
{
    publicclass Blog
    {
        publicint BlogId { get; set; }
        publicstring Name { get; set; }         
        publicstring Url { get; set; }
        public int Rating { get; set; }        public List<Post> Posts { get; set; }
    }

    public class Post    {        public int PostId { get; set; }        [MaxLength(200)]        public string Title { get; set; }        public string Content { get; set; }        public int BlogId { get; set; }        public Blog Blog { get; set; }    }
}

2. 使用 Add-Migration 命令建立一個遷移,命名為 AddPostClass。


3.  Code First Migrations 幫我們建立好了一個遷移,但是我們希望能增加如下的修改:

     首先,為 Posts.Title 增加一個唯一索引。

     增加一個非空的 Blogs.Rating 列,如果表中已經存在了資料,那麼就將 CLR 預設的資料型別值賦予新增加的列 (Rating 是整數型別,應該就是 0), 但是,我們希望預設為 3, 這樣已經存在的部落格會有一個不錯的評分。

namespace MigrationsCodeDemo.Migrations
{
    using System.Data.Entity.Migrations;

    publicpartialclass AddPostClass : DbMigration
    {
        publicoverridevoid Up()
        {
            CreateTable(
                "Posts",
                c => new
                {
                    PostId = c.Int(nullable: false, identity: true),
                    Title = c.String(maxLength: