Entity Framework使用Code First模式管理數(shù)據(jù)庫
一、管理數(shù)據(jù)庫連接
1、使用配置文件管理連接之約定
在數(shù)據(jù)庫上下文類中,如果我們只繼承了無參數(shù)的DbContext,并且在配置文件中創(chuàng)建了和數(shù)據(jù)庫上下文類同名的連接字符串,那么EF會(huì)使用該連接字符串自動(dòng)計(jì)算出數(shù)據(jù)庫的位置和數(shù)據(jù)庫名。比如,我們的數(shù)據(jù)庫上下文定義如下:
using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConventionConfigure.EF { /// <summary> /// 繼承無參數(shù)的DbContext /// </summary> public class SampleDbEntities :DbContext { public SampleDbEntities() { // 數(shù)據(jù)庫不存在時(shí)創(chuàng)建數(shù)據(jù)庫 Database.CreateIfNotExists(); } } }
在配置文件中定義的連接字符串如下:
<connectionStrings> <add name="SampleDbEntities" connectionString="Data Source=.;Initial Catalog=TestDb;Integrated Security=True;MultipleActiveResultSets=True" providerName="System.Data.SqlClient" /> </connectionStrings>
定義的連接字符串中name的value值和創(chuàng)建的數(shù)據(jù)庫上下文類的類名相同,這樣EF會(huì)使用該連接字符串執(zhí)行數(shù)據(jù)庫操作,究竟會(huì)發(fā)生什么呢?
運(yùn)行程序,Program類定義如下:
using ConventionConfigure.EF; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConventionConfigure { class Program { static void Main(string[] args) { using (var context = new SampleDbEntities()) { } Console.WriteLine("創(chuàng)建成功"); Console.ReadKey(); } } }
當(dāng)運(yùn)行應(yīng)用程序時(shí),EF會(huì)尋找我們的數(shù)據(jù)庫上下文類,即“SampleDbEntities”,并在配置文件中尋找和它同名的連接字符串,然后它會(huì)使用該連接字符串計(jì)算出應(yīng)該使用哪個(gè)數(shù)據(jù)庫provider,之后檢查數(shù)據(jù)庫位置,之后會(huì)在指定的位置創(chuàng)建一個(gè)名為TestDb.mdf的數(shù)據(jù)庫文件,同時(shí)根據(jù)連接字符串的Initial Catalog屬性創(chuàng)建了一個(gè)名為TestDb的數(shù)據(jù)庫。創(chuàng)建的數(shù)據(jù)庫結(jié)構(gòu)如下:
查看創(chuàng)建后的數(shù)據(jù)庫,會(huì)發(fā)現(xiàn)只有一張遷移記錄表。
2、使用已經(jīng)存在的ConnectionString
如果我們已經(jīng)有了一個(gè)定義數(shù)據(jù)庫位置和名稱的ConnectionString,并且我們想在數(shù)據(jù)庫上下文類中使用這個(gè)連接字符串,連接字符串如下:
<connectionStrings> <add name="AppConnection" connectionString="Data Source=.;Initial Catalog=TestDb;Integrated Security=True;MultipleActiveResultSets=True" providerName="System.Data.SqlClient" /> </connectionStrings>
以上面創(chuàng)建的數(shù)據(jù)庫TestDb作為已經(jīng)存在的數(shù)據(jù)庫,新添加實(shí)體類Student,使用已經(jīng)存在的ConnectionString查詢數(shù)據(jù)庫的Student表,Student實(shí)體類定義如下:
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ExistsConnectionString.Model { [Table("Student")] public class Student { public int Id { get; set; } public string Name { get; set; } public string Sex { get; set; } public int Age { get; set; } } }
我們將該連接字符串的名字傳入數(shù)據(jù)庫上下文DbContext的有參構(gòu)造函數(shù)中,數(shù)據(jù)庫上下文類定義如下:
using ExistsConnectionString.Model; using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ExistsConnectionString.EF { public class SampleDbEntities : DbContext { public SampleDbEntities() : base("name=AppConnection") { } // 添加到數(shù)據(jù)上下文中 public virtual DbSet<Student> Students { get; set; } } }
上面的代碼將連接字符串的名字傳給了DbContext類的有參構(gòu)造函數(shù),這樣一來,我們的數(shù)據(jù)庫上下文就會(huì)開始使用該連接字符串了,在Program類中輸出Name和Age字段的值:
using ExistsConnectionString.EF; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ExistsConnectionString { class Program { static void Main(string[] args) { using (var context = new SampleDbEntities()) { foreach (var item in context.Students) { Console.WriteLine("姓名:"+item.Name+" "+"年齡:"+item.Age); } } } } }
運(yùn)行程序,發(fā)現(xiàn)會(huì)報(bào)下面的錯(cuò)誤:
出現(xiàn)上面報(bào)錯(cuò)的原因是因?yàn)閿?shù)據(jù)庫上下文發(fā)生了改變,與現(xiàn)有數(shù)據(jù)庫不匹配。解決方案:
把數(shù)據(jù)庫里面的遷移記錄表刪掉或者重命名即可。
重新運(yùn)行程序,結(jié)果如下:
注意:如果在配置文件中還有一個(gè)和數(shù)據(jù)庫上下文類名同名的ConnectionString,那么就會(huì)使用這個(gè)同名的連接字符串。無論我們對(duì)傳入的連接字符串名稱如何改變,都是無濟(jì)于事的,也就是說和數(shù)據(jù)庫上下文類名同名的連接字符串優(yōu)先權(quán)更大。(即約定大于配置)
3、使用已經(jīng)存在的連接
通常在一些老項(xiàng)目中,我們只會(huì)在項(xiàng)目中的某個(gè)部分使用EF Code First,同時(shí),我們想對(duì)數(shù)據(jù)上下文類使用已經(jīng)存在的數(shù)據(jù)庫連接,如果要實(shí)現(xiàn)這個(gè),可將連接對(duì)象傳給DbContext類的構(gòu)造函數(shù),數(shù)據(jù)上下文定義如下:
using ExistsDbConnection.Model; using System; using System.Collections.Generic; using System.Data.Common; using System.Data.Entity; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ExistsDbConnection.EF { public class SampleDbEntities :DbContext { public SampleDbEntities(DbConnection con) : base(con, contextOwnsConnection: false) { } public virtual DbSet<Student> Students { get; set; } } }
這里要注意一下contextOwnsConnection參數(shù),之所以將它作為false傳入到上下文,是因?yàn)樗菑耐獠總魅氲模?dāng)上下文超出了范圍時(shí),可能會(huì)有人想要使用該連接。如果傳入true的話,那么一旦上下文出了范圍,數(shù)據(jù)庫連接就會(huì)立即關(guān)閉。
Program類定義如下:
using System; using System.Collections.Generic; using System.Data.Common; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Configuration; using ExistsDbConnection.EF; namespace ExistsDbConnection { class Program { static void Main(string[] args) { // 讀取連接字符串 string conn = ConfigurationManager.ConnectionStrings["AppConnection"].ConnectionString; // DbConnection是抽象類,不能直接實(shí)例化,聲明子類指向父類對(duì)象 DbConnection con = new SqlConnection(conn); using (var context = new SampleDbEntities(con)) { foreach (var item in context.Students) { Console.WriteLine("姓名:" + item.Name + " " + "年齡:" + item.Age); } } Console.WriteLine("讀取完成"); Console.ReadKey(); } } }
運(yùn)行程序,結(jié)果如下:
二、管理數(shù)據(jù)庫創(chuàng)建
首次運(yùn)行EF Code First應(yīng)用時(shí),EF會(huì)做下面的這些事情:
1、檢查正在使用的DbContext類。
2、找到該上下文類使用的connectionString。
3、找到領(lǐng)域?qū)嶓w并提取模式相關(guān)的信息。
4、創(chuàng)建數(shù)據(jù)庫。
5、將數(shù)據(jù)插入系統(tǒng)。
一旦模式信息提取出來,EF會(huì)使用數(shù)據(jù)庫初始化器將該模式信息推送給數(shù)據(jù)庫。數(shù)據(jù)庫初始化器有很多可能的策略,EF默認(rèn)的策略是如果數(shù)據(jù)庫不存在,那么就重新創(chuàng)建;如果存在的話就使用當(dāng)前存在的數(shù)據(jù)庫。當(dāng)然,我們有時(shí)也可能需要覆蓋默認(rèn)的策略,可能用到的數(shù)據(jù)庫初始化策略如下:
CreateDatabaseIfNotExists:CreateDatabaseIfNotExists:顧名思義,如果數(shù)據(jù)庫不存在,那么就重新創(chuàng)建,否則就使用現(xiàn)有的數(shù)據(jù)庫。如果從領(lǐng)域模型中提取到的模式信息和實(shí)際的數(shù)據(jù)庫模式不匹配,那么就會(huì)拋出異常。
DropCreateDatabaseAlways:如果使用了該策略,那么每次運(yùn)行程序時(shí),數(shù)據(jù)庫都會(huì)被銷毀。這在開發(fā)周期的早期階段通常很有用(比如設(shè)計(jì)領(lǐng)域?qū)嶓w時(shí)),從單元測(cè)試的角度也很有用。
DropCreateDatabaseIfModelChanges:這個(gè)策略的意思就是說,如果領(lǐng)域模型發(fā)生了變化(具體而言,從領(lǐng)域?qū)嶓w提取出來的模式信息和實(shí)際的數(shù)據(jù)庫模式信息失配時(shí)),就會(huì)銷毀以前的數(shù)據(jù)庫(如果存在的話),并創(chuàng)建新的數(shù)據(jù)庫。
MigrateDatabaseToLatestVersion:如果使用了該初始化器,那么無論什么時(shí)候更新實(shí)體模型,EF都會(huì)自動(dòng)地更新數(shù)據(jù)庫模式。這里很重要的一點(diǎn)是:這種策略更新數(shù)據(jù)庫模式不會(huì)丟失數(shù)據(jù),或者是在已有的數(shù)據(jù)庫中更新已存在的數(shù)據(jù)庫對(duì)象。MigrateDatabaseToLatestVersion初始化器只有從EF4.3才可用。
1、設(shè)置初始化策略
EF默認(rèn)使用CreateDatabaseIfNotExists作為默認(rèn)初始化器,如果要覆蓋這個(gè)策略,那么需要在DbContext類中的構(gòu)造函數(shù)中使用Database.SetInitializer方法,下面的例子使用DropCreateDatabaseIfModelChanges策略覆蓋默認(rèn)的策略。數(shù)據(jù)庫上下文類定義如下:
using InitializationStrategy.Model; using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Text; using System.Threading.Tasks; namespace InitializationStrategy.EF { public class SampleDbEntities : DbContext { public SampleDbEntities() : base("name=AppConnection") { // 使用DropCreateDatabaseIfModelChanges策略覆蓋默認(rèn)的策略 Database.SetInitializer<SampleDbEntities>(new DropCreateDatabaseIfModelChanges<SampleDbEntities>()); } // 添加到數(shù)據(jù)上下文中 public virtual DbSet<Student> Students { get; set; } } }
這樣一來,無論什么時(shí)候創(chuàng)建上下文類,Database.SetInitializer()方法都會(huì)被調(diào)用,并且將數(shù)據(jù)庫初始化策略設(shè)置為DropCreateDatabaseIfModelChanges。
Student領(lǐng)域?qū)嶓w類新增加Email和Address兩個(gè)屬性:
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Text; using System.Threading.Tasks; namespace InitializationStrategy.Model { [Table("Student")] public class Student { public int Id { get; set; } public string Name { get; set; } public string Sex { get; set; } public int Age { get; set; } public string Email { get; set; } public string Address { get; set; } } }
Program類定義如下:
using InitializationStrategy.EF; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace InitializationStrategy { class Program { static void Main(string[] args) { using (var context = new SampleDbEntities()) { foreach (var item in context.Students) { } } Console.WriteLine("創(chuàng)建成功"); Console.ReadKey(); } } }
運(yùn)行程序后,數(shù)據(jù)庫表結(jié)構(gòu)如下:
注意:如果處于生產(chǎn)環(huán)境,那么我們肯定不想丟失已經(jīng)存在的數(shù)據(jù)。這時(shí)我們就需要關(guān)閉該初始化器,只需要將null傳給Database.SetInitlalizer()方法,如下所示:
public SampleDbEntities(): base("name=AppConnection") { Database.SetInitializer<SampleDbEntities>(null); }
2、填充種子數(shù)據(jù)
到目前為止,無論我們選擇哪種策略初始化數(shù)據(jù)庫,生成的數(shù)據(jù)庫都是一個(gè)空的數(shù)據(jù)庫。但是許多情況下我們總想在數(shù)據(jù)庫創(chuàng)建之后、首次使用之前就插入一些數(shù)據(jù)。此外,開發(fā)階段可能想以admin的資格為其填充一些數(shù)據(jù),或者為了測(cè)試應(yīng)用在特定的場(chǎng)景中表現(xiàn)如何,想要偽造一些數(shù)據(jù)。
當(dāng)我們使用DropCreateDatabaseAlways和DropCreateDatabaseIfModelChanges初始化策略時(shí),插入種子數(shù)據(jù)非常重要,因?yàn)槊看芜\(yùn)行應(yīng)用時(shí),數(shù)據(jù)庫都要重新創(chuàng)建,每次數(shù)據(jù)庫創(chuàng)建之后在手動(dòng)插入數(shù)據(jù)非常乏味。接下來我們看一下當(dāng)數(shù)據(jù)庫創(chuàng)建之后如何使用EF來插入種子數(shù)據(jù)。
為了向數(shù)據(jù)庫插入一些初始化數(shù)據(jù),我們需要?jiǎng)?chuàng)建滿足下列條件的數(shù)據(jù)庫初始化器類:
1、從已存在的數(shù)據(jù)庫初始化器類中派生數(shù)據(jù)。
2、在數(shù)據(jù)庫創(chuàng)建期間種子化。
下面演示如何初始化種子數(shù)據(jù)
1、定義領(lǐng)域?qū)嶓w類
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Text; using System.Threading.Tasks; namespace InitializationSeed.Model { [Table("Employee")] public class Employee { public int EmployeeId { get; set; } public string FirstName { get; set; } public string LastName { get; set; } } }
2、創(chuàng)建數(shù)據(jù)庫上下文
使用EF的Code First方式對(duì)上面的模型創(chuàng)建數(shù)據(jù)庫上下文:
public class SampleDbEntities : DbContext { public virtual DbSet<Employee> Employees { get; set; } }
3、創(chuàng)建數(shù)據(jù)庫初始化器類
假設(shè)我們使用的是DropCreateDatabaseAlways數(shù)據(jù)庫初始化策略,那么初始化器類就要從該泛型類繼承,并傳入數(shù)據(jù)庫上下文作為類型參數(shù)。接下來,要種子化數(shù)據(jù)庫就要重寫DropCreateDatabaseAlways類的Seed()方法,而Seed()方法拿到了數(shù)據(jù)庫上下文,因此我們可以使用它來將數(shù)據(jù)插入數(shù)據(jù)庫:
using InitializationSeed.Model; using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Text; using System.Threading.Tasks; namespace InitializationSeed.EF { /// <summary> /// 數(shù)據(jù)庫初始化器類 /// </summary> public class SeedingDataInitializer : DropCreateDatabaseAlways<SampleDbEntities> { /// <summary> /// 重寫DropCreateDatabaseAlways的Seed方法 /// </summary> /// <param name="context"></param> protected override void Seed(SampleDbEntities context) { for (int i = 0; i < 6; i++) { var employee = new Employee { FirstName="測(cè)試"+(i+1), LastName="工程師" }; context.Employees.Add(employee); } base.Seed(context); } } }
上面的代碼通過for循環(huán)創(chuàng)建了6個(gè)Employee對(duì)象,并將它們添加給數(shù)據(jù)庫上下文類的Employees集合屬性。這里值得注意的是我們并沒有調(diào)用DbContext.SaveChanges()方法,因?yàn)樗鼤?huì)在基類中自動(dòng)調(diào)用。
4、將數(shù)據(jù)庫初始化器類用于數(shù)據(jù)庫上下問類
using InitializationSeed.Model; using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Text; using System.Threading.Tasks; namespace InitializationSeed.EF { public class SampleDbEntities :DbContext { public SampleDbEntities() : base("name=AppConnection") { // 類型傳SeedingDataInitializer Database.SetInitializer<SampleDbEntities>(new SeedingDataInitializer()); } // 領(lǐng)域?qū)嶓w添加到數(shù)據(jù)上下文中 public virtual DbSet<Employee> Employees { get; set; } } }
5、Main方法中訪問數(shù)據(jù)庫
using InitializationSeed.EF; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace InitializationSeed { class Program { static void Main(string[] args) { using (var context = new SampleDbEntities()) { foreach (var item in context.Employees) { Console.WriteLine("FirstName:"+item.FirstName+" "+"LastName:"+item.LastName); } } Console.WriteLine("讀取完成"); Console.ReadKey(); } } }
6、運(yùn)行程序,查看結(jié)果
查看數(shù)據(jù)庫
種子數(shù)據(jù)填充完成。
7、使用數(shù)據(jù)遷移的方式填充種子數(shù)據(jù)
使用數(shù)據(jù)遷移的方式會(huì)生成Configuration類,Configuration類定義如下:
namespace DataMigration.Migrations { using System; using System.Data.Entity; using System.Data.Entity.Migrations; using System.Linq; internal sealed class Configuration : DbMigrationsConfiguration<DataMigration.SampleDbEntities> { public Configuration() { AutomaticMigrationsEnabled = false; } protected override void Seed(DataMigration.SampleDbEntities context) { // This method will be called after migrating to the latest version. // You can use the DbSet<T>.AddOrUpdate() helper extension method // to avoid creating duplicate seed data. } } }
重寫Configuration類的Seed()方法也可以實(shí)現(xiàn)插入種子數(shù)據(jù),重寫Seed()方法:
namespace DataMigration.Migrations { using DataMigration.Model; using System; using System.Data.Entity; using System.Data.Entity.Migrations; using System.Linq; internal sealed class Configuration : DbMigrationsConfiguration<DataMigration.SampleDbEntities> { public Configuration() { AutomaticMigrationsEnabled = false; } protected override void Seed(DataMigration.SampleDbEntities context) { // This method will be called after migrating to the latest version. // You can use the DbSet<T>.AddOrUpdate() helper extension method // to avoid creating duplicate seed data. context.Employees.AddOrUpdate( new Employee { FirstName = "測(cè)試1", LastName = "工程師" }, new Employee { FirstName = "測(cè)試2", LastName = "工程師" } ); } } }
使用數(shù)據(jù)遷移,然后查看數(shù)據(jù)庫結(jié)果:
發(fā)現(xiàn)使用數(shù)據(jù)遷移的方式也將種子數(shù)據(jù)插入到了數(shù)據(jù)庫中。
代碼下載地址:點(diǎn)此下載
到此這篇關(guān)于Entity Framework使用Code First模式管理數(shù)據(jù)庫的文章就介紹到這了。希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- Entity?Framework代碼優(yōu)先(Code?First)模式
- Entity Framework使用Code First模式管理事務(wù)
- Entity Framework使用Code First模式管理存儲(chǔ)過程
- Entity Framework使用Code First模式管理視圖
- Entity?Framework使用Code?First的實(shí)體繼承模式
- EF使用Code First模式生成單數(shù)形式表名
- EF使用Code First模式給實(shí)體類添加復(fù)合主鍵
- 使用EF的Code?First模式操作數(shù)據(jù)庫
- C#筆記之EF Code First 數(shù)據(jù)模型 數(shù)據(jù)遷移
- Entity?Framework代碼優(yōu)先Code?First入門
相關(guān)文章
VS2010、VS2008等項(xiàng)目的默認(rèn)瀏覽器修改方法(圖文)
默認(rèn)情況下,VS會(huì)使用操作系統(tǒng)的默認(rèn)瀏覽器,但我在調(diào)試 ASP.NET 程序時(shí)更偏向于使用IE瀏覽器,下面與大家分享下VS2010、VS2008等項(xiàng)目的默認(rèn)瀏覽器的修改方法2013-05-05詳解ASP.NET Core 在 JSON 文件中配置依賴注入
本篇文章主要介紹了詳解ASP.NET Core 在 JSON 文件中配置依賴注入 ,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-02-02ASP.NET Core2靜默獲取微信公眾號(hào)的用戶OpenId實(shí)例代碼
這篇文章主要給大家介紹了關(guān)于ASP.NET Core2靜默獲取微信公眾號(hào)的用戶OpenId的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2018-12-12微信公眾平臺(tái)開發(fā)之處理圖片.Net代碼解析
這篇文章主要為大家詳細(xì)解析了微信公眾平臺(tái)開發(fā)之處理圖片.Net代碼,感興趣的小伙伴們可以參考一下2016-06-06Linux下部署.net core環(huán)境的步驟詳解
這篇文章主要給大家介紹了在Linux下部署.net core環(huán)境的步驟,文中給出了詳細(xì)的介紹,相信對(duì)大家的學(xué)習(xí)或者工作具有一定的參考價(jià)值,需要的朋友們下面來一起看看吧。2017-04-04