MVC - 10.CodeFrist


微軟示例

1.(對新數據庫使用 Code First):http://msdn.microsoft.com/zh-cn/data/jj193542

2.(連接和模型):http://msdn.microsoft.com/zh-cn/data/jj592674.aspx

 

1.安裝EF 5.0

打開“程序包管理器控制台”,(“視圖”-》“其他窗口”-》“程序包管理器控制台”)
MVC4只能安裝 EF 5.0

Install-Package EntityFramework -Version 5.0.0

 

Uninstall-Package

刪除一個包,使用Uninstall-Package命令包的名稱。例如,使用Uninstall-Package elmah命令下面的例子所示:

image

 

下列是安裝了6.1.1,結果MVC4只支持5.0.0

PM> Uninstall-Package EntityFramework
正在從 05MVCAjax_CodeFirst 刪除“EntityFramework 6.1.1”。
已成功將“EntityFramework 6.1.1”從 05MVCAjax_CodeFirst 中刪除。
正在卸載“EntityFramework 6.1.1”。
已成功卸載“EntityFramework 6.1.1”。

PM> Install-Package EntityFramework -Version 5.0.0
正在安裝“EntityFramework 5.0.0”。
您正在從 Microsoft 下載 EntityFramework,有關此程序包的許可協議在 http://go.microsoft.com/fwlink/?LinkId=253898&clcid=0x409 上提供。請檢查此程序包是否有其他依賴項,這些依賴項可能帶有各自的許可協議。您若使用程序包及依賴項,即構成您接受其許可協議。如果您不接受這些許可協議,請從您的設備中刪除相關組件。
已成功安裝“EntityFramework 5.0.0”。
正在將“EntityFramework 5.0.0”添加到 05MVCAjax_CodeFirst。
已成功將“EntityFramework 5.0.0”添加到 05MVCAjax_CodeFirst。

 

2.創建模型

image

 

Classe.cs
Classe.cs

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity;
using System.Linq;
using System.Web;

namespace _05MVCAjax_CodeFirst.Models
{
    public class Student
    {
        [Key]
        public int StudentID { get; set; }
        public int Cid { get; set; }
        public string Name { get; set; }
        public string Gender { get; set; }
        public int Isdel { get; set; }
        public DateTime AddTime { get; set; }

        public virtual Classe Classes { get; set; }
    }
}

 

2.1.StudentID 如果寫成 StudentId 這樣寫能與外鍵列名保持一致,感覺這樣好點。(這里我只能加[Key])

image

2.2.類名用的是Classe,而不是Classes。實體一般用單數,在生成數據表是,會自動添加成復數表名 Classes

 

 

Student.cs
Student.cs

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity;
using System.Linq;
using System.Web;

namespace _05MVCAjax_CodeFirst.Models
{
    public class Student
    {
        [Key]
        public int StudentID { get; set; }
        public int Cid { get; set; }
        public string Name { get; set; }
        public string Gender { get; set; }
        public int Isdel { get; set; }
        public DateTime AddTime { get; set; }

        public virtual Classe Classes { get; set; }
    }
}

 

2.3.virtual 用於延遲加載,也就是你在使用 Student 實體對象時,如果不使用相關聯的 Classe 表中的數據,系統就不加載,你使用的時候,才到數據庫查詢相應的 Classe 數據。

 

3.創建上下文

現在,可以定義派生上下文,用於表示數據庫的一個會話,以便我們查詢和保存數據。我們定義一個派生自 System.Data.Entity.DbContext 的上下文,並為模型中的每個類公開一個類型化 DbSet<TEntity>。

image

AppContext.cs
AppContext.cs

using System;
using System.Collections.Generic;
using System.Data.Entity;   //DbContext
using System.Linq;
using System.Web;

namespace _05MVCAjax_CodeFirst.Models
{
    public class AppContext : DbContext
    {
        public AppContext()
            : base("name=AppContext") { }
        public DbSet<Classe> Classes { get; set; }
        public DbSet<Student> Students { get; set; }
    }
}

 

image

 

image

 

4.處理模型更改

現在更改模型,當我們進行更改時,還需要更新數據庫架構。為此,我們使用一個稱為“Code First 遷移”(或簡稱“遷移”)的功能。

“遷移”是一組有序的步驟,描述如何升級(和降級)數據庫架構。這些步驟(稱為“遷移”)中的每個步驟均包含一些代碼,用於描述要應用的更改。

第一步是為 AppContext 啟用 Code First 遷移。

  • “工具”->“庫程序包管理器”->“程序包管理器控制台”
  • 在程序包管理器控制台中運行 Enable-Migrations 命令

一個新的 Migrations 文件夾已添加至項目中,它包含兩個文件:

  • Configuration.cs — 此文件包含“遷移”將用來遷移 BloggingContext 的設置。在本演練中不需要進行任何更改,但是,在此處可以指定種子數據、為其他數據庫注冊提供程序、更改生成遷移的命名空間等。
  • <時間戳>_InitialCreate.cs — 這是第一個遷移,它表示已經應用於數據庫的更改。應用更改的目的是將其從空數據庫遷移至包含博客和文章表的數據庫(這句話說的microsoft里面的示例)。盡管我們讓 Code First 自動創建這些表,現在我們選擇“遷移”(已轉化為一次“遷移”)。Code First 還在本地數據庫中記錄:該“遷移”已經應用。文件名中的時間戳用於排序。

image


現在,更改模型,向 Student 類添加一個 Mark 屬性:

image

在程序包管理器控制台中運行 Add-Migration AddUrl 命令。
Add-Migration 命令檢查自上次遷移后是否有更改,並使用所有更改搭建新遷移。我們可以為遷移指定名稱;在本例中,將此遷移稱為“AddUrl”。
搭建的代碼表明:我們需要向 dbo.Blogs 表添加可容納字符串數據的 Url 列。如果需要,可以對搭建的代碼進行編輯,但是,在本例中,沒有這個必要。

Migrations/201407100246388_AddUrl.cs
Migrations/201407100246388_AddUrl.cs

namespace _05MVCAjax_CodeFirst.Migrations
{
    using System;
    using System.Data.Entity.Migrations;
    
    public partial class AddUrl : DbMigration
    {
        public override void Up()
        {
            AddColumn("dbo.Students", "Mark", c => c.String());
        }
        
        public override void Down()
        {
            DropColumn("dbo.Students", "Mark");
        }
    }
}

 

在程序包管理器控制台中運行 Update-Database 命令。此命令將所有掛起的遷移應用於數據庫。InitialCreate 遷移已經應用,因此,這些遷移將僅應用新的 AddUrl 遷移。
提示:在調用 Update-Database 命令查看對數據庫執行的 SQL 時,可以使用 –Verbose 開關。

image

 

5.數據注釋

到目前為止,EF 發現了使用其默認約定的模型。但是,有時類不遵從約定,我們需要能夠執行進一步配置。對此有兩種方法;本節將介紹數據注釋,下一節將介紹 Fluent API。

向模型添加用戶類

public class User
    {
        public string Username { get; set; }
        public string DisplayName { get; set; }
    }

我們還需要向派生上下文添加一個集

public class BloggingContext : DbContext
    {
        public DbSet<Blog> Blogs { get; set; }
        public DbSet<Post> Posts { get; set; }
        public DbSet<User> Users { get; set; }
    }

如果嘗試添加遷移,會收到錯誤消息“EntityType‘User’未定義鍵。請為該 EntityType 定義鍵。”這是因為 EF 無法知道 Username 應為用戶的主鍵。

我們將使用數據注釋,因此需要在 Program.cs 的頂部添加一個 using 語句

using System.ComponentModel.DataAnnotations;

現在,注釋 Username 屬性,將它標識為主鍵

public class User
    {
        [Key]
        public string Username { get; set; }
        public string DisplayName { get; set; }
    }

使用 Add-Migration AddUser 命令搭建一個遷移,將這些更改應用於數據庫

運行 Update-Database 命令,將新遷移應用於數據庫

現在,新表已添加至數據庫:

顯示在服務器資源管理器中的架構

EF 支持的完整注釋列表為:

 

6.Fluent API(模型配置方法)

上一節介紹了如何使用數據注釋來補充或重寫按約定檢測的內容。另一種模型配置方法是通過 Code First Fluent API。

大多數模型配置都可使用簡單數據注釋進行。Fluent API 是一種更高級的方法,除某些數據注釋不可能支持的更高級配置外,可以指定包含數據注釋所有功能的模型配置。數據注釋和 Fluent API 可一起使用。

要訪問 Fluent API,需要在 DbContext 中重寫 OnModelCreating 方法。假設我們需要重命名 User.DisplayName 存儲至 display_name 的列。

  • 使用以下代碼重寫 BloggingContext 的 OnModelCreating 方法
public class BloggingContext : DbContext 
        { public DbSet<Blog> Blogs { get; set; } 
            public DbSet<Post> Posts { get; set; } 
            public DbSet<User> Users { get; set; } 
            protected override void OnModelCreating(DbModelBuilder modelBuilder) 
            { 
                modelBuilder.Entity<User>()
                    .Property(u => u.DisplayName)
                    .HasColumnName("display_name"); 
            }
        }
  • 使用 Add-Migration ChangeDisplayName 命令搭建遷移,將這些更改應用於數據庫。
  • 運行 Update-Database 命令,將新遷移應用於數據庫。

DisplayName 列現在重命名為 display_name:

image

 

 

7、修改表結構Update-Database(自動遷移容易導致數據丟失)

1、設置好數據庫連接字串

在項目中,找到 app.config(沒有則在項目根目錄手動新增,這里的設置只對本項目有效,不會影響到 Web 項目中的設置)。配置 <connectionStrings> 節點,新增

<connectionStrings>
    <add name="AppContext" connectionString="Data Source=.;Initial Catalog=Test;User ID=sa;Password=sa123" providerName="System.Data.SqlClient" />
  </connectionStrings>

,Mvc4DAL 用的是名稱 AppContext的連接字串

public class AppContext : DbContext
    {
        public AppContext()
            : base("name=AppContext") { }

若沒有設置好連接字串,或是字串設置有誤,將出現如下提示:
Anerror occurred while getting provider information from the database. This canbe caused by Entity Framework using an incorrect connection string. Check theinner exceptions for details and ensure that the connection string is correct.

2、運行命令Enable-Migrations

出現如下提示時,你需要執行 Enable-Migrations
Nomigrations configuration type was found in the assembly 'Mvc4DAL'. (In VisualStudio you can use the Enable-Migrations command from Package Manager Consoleto add a migrations configuration).

打開“程序包管理器控制台”,運行命令 Enable-Migrations ,Mvc4DAL項目中將出現Migrations文件夾與相應的文件 Configuration.cs
image

 

執行 Enable-Migrations 時可能會因為錯誤而打斷,此時需要再次運行加參數的命令Enable-Migrations -Force:
Migrationshave already been enabled in project 'Mvc4DAL'. To overwrite the existingmigrations configuration, use the -Force parameter.

注意“Enable-Migrations”中間沒有空格,“-Force”前面必須要有空格。

3、設置 AutomaticMigrationsEnabledtrue (自動遷移容易導致數據丟失,最好還是用Add-Migration)

打開Migrations文件夾中的 Configuration.cs,AutomaticMigrationsEnabled默認為 false 改為 true就哦了,否則將出現提示:
Unable to update database to match the current model because there arepending changes and automatic migration is disabled. Either write the pendingmodel changes to a code-based migration or enable automatic migration. SetDbMigrationsConfiguration.AutomaticMigrationsEnabled to true to enableautomatic migration. You can use the Add-Migration command to write the pendingmodel changes to a code-based migration.

四、最后執行 Update-Database

上述步驟都設置好了,打開“程序包管理器控制台”,運行命令 Update-Database,沒有出錯就大功成。這里要注意的是,數據庫中有個名稱為dbo.__MigrationHistory 的Table很重要,記錄的是從創建數據庫開始的全部更新的記錄,所以在你沒有絕對把握的情況下千萬別動它。

 

 

 

8.問題解決:

1.安裝了6.1.1后,報錯。

---------------------------
Microsoft Visual Studio
---------------------------
無法檢索“_05MVCAjax_CodeFirst.Models.Student”的元數據。無法識別的元素“providers”。 (C:\Users\TANGGE\AppData\Local\Temp- mp5C01.tmp line 52)
---------------------------
確定  
---------------------------

 

注釋掉Web.Config里面的<providers>

  </system.webServer>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="v11.0" />
      </parameters>
    </defaultConnectionFactory>
    <!--<providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>-->
  </entityFramework>
</configuration>

 

 

2.缺少主鍵。

無法檢索“_05MVCAjax_CodeFirst.Models.Student”的元數據。

One or more validation errors were detected during model generation:
- System.Data.Entity.Edm.EdmEntityType: : EntityType 'Classe' has no key defined. Define the key for this EntityType.
- System.Data.Entity.Edm.EdmEntitySet: EntityType: EntitySet 'Classes' is based on type 'Classe' that has no keys defined.
Type 'get-help EntityFramework' to see all available Entity Framework commands.

 

 

3.版本問題。

image

解決方案:

卸載6.1.1,重裝5.0.0,(如果已經完成可不操作),重啟vs。

 

Code First 從數據庫自動生成工具EF Power Tools 4

http://pan.baidu.com/s/1dCP1G

EF Power Tools學習資料

http://msdn.microsoft.com/zh-cn/data/jj593170.aspx


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM