Entity Framework框架提供了幾種開發模式,比如Database First,Model First,Code First,Database First是最老也是應用得最廣泛的一種設計方式,Database First這種方式的設計高度依賴于資料庫中表的結構,根據表及表間的關系來創建模型,如果后期需求有所變更或者功能有很大變化的話,需要涉及到更改資料庫所付出的代價將會很大,因為之前撰寫好的代碼將不再適用于新的表,我們必需重構以更改代碼中的邏輯以適應更改之后的表,Model First是創建ADO.NET物體物件以及它們之間的關系,然后再指定到資料庫的映射,這個物體物件即為Model,
我們今天要講的是Code First(代碼先行),它思想就是先定義模型中的類,再通過這些類生成資料庫,這種開發模式適合于全新的專案,它使得我們可以以代碼為核心進行設計而不是先構造資料庫,步驟如下,
1.接下來我就以一個簡單的例子來介紹這種開發模式,我們的需求是兩個表,博客表和評論表,一個博客對應多個評論,一個評論對應一個博客,這是一對多關系,我們先新建一個ASP.NET MVC專案,并用NuGet安裝EntityFramework,然后建立兩個Model,
public class Blog { [Key] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public Guid Id { get; set; } public string Title { get; set; } public string Author { get; set; } public DateTime Time { get; set; } public string Summary { get; set; } public string Content { get; set; } public virtual ICollection<Comment> Comments { get; set; } = new List<Comment>(); }
public class Comment { [Key] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public Guid Id { get; set; } public string VisitorName { get; set; } public string Email { get; set; } public DateTime Time { get; set; } public string Content { get; set; } [ForeignKey("Blog")] public Guid BlogId { get; set; } public virtual Blog Blog { get; set; } }
2.接下來我們創建資料背景關系,新建一個檔案夾叫Context,并在其中新建類,代碼如下:
public class TestDbContext: DbContext { public TestDbContext() : base("name=ConString") { } #region 資料庫相關表 新增表需要在此添加對應關系 public virtual DbSet<Blog> Blog{ get; set; } public virtual DbSet<Comment>Comment{ get; set; }
#endregion }
3.接著我們在Web.config中來配置資料庫,在Web.config中的<configuration>節點中加入如下配置(注意:section節點和connectionStrings的位置)
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework"
type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
requirePermission="false"/>
</configSections>
<connectionStrings>
<add name="ConString" connectionString="Server=.;DataBase=test;Uid=sa;Pwd=123456" providerName="System.Data.SqlClient" />
</connectionStrings>
4.添加完成之后,進行資料遷移
打開Package Manager Console(程式包管理控制臺)

輸入命令 1、 enable-migrations 回車,2、add-migration 回車,輸入方便認識的名字 ,3、下面我們就執行正式遷移,輸入 update-database 回車,搞定,
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/1667.html
上一篇:EF--封裝三層架構IOC
