標籤:entity framework code first
EF(Entity Framework)是微軟以 ADO.NET 為基礎所發展出來的對象關係對應 (O/R Mapping(對象關係映射(Object RelationalMapping,簡稱ORM)是一種為瞭解決物件導向與關聯式資料庫存在的互不匹配的現象的技術。)) 解決方案。
Entity Framework利用了抽象化資料結構的方式,將每個資料庫物件都轉換成應用程式物件 (entity),而資料欄位都轉換為屬性 (property),關係則轉換為結合屬性(association),讓資料庫的 E/R 模型完全的轉成物件模型。它有三種產生模式,分別為Database First、Model First、CodeFirst,那麼今天我們就來實現Code First。所謂Code First就是說用代碼來直接去建立資料庫並進行EF映射。
首先我們先來添加兩個實體類,代碼如下:
訂單類
public class OrderInfo { [Key] public int Id { get; set; } public string Content { get; set; } /// <summary> /// 外鍵 /// </summary> public int CustomerId { get; set; } public Customer Customer { get; set; } }
客戶類
public class Customer { [Key] public int Id {get;set;} public string CusName { get; set; } public virtualICollection<OrderInfo> Order { get; set; } }
這裡的[Key]是標識符的意思,也就是設定主鍵,這裡要添加引用System.ComponentModel.DataAnnotations
接下來我們就自訂一個資料庫上下文
public classHotelDbContext:DbContext { public HotelDbContext() :base("name=ConnCodeFirst") { } public DbSet<Customer> Customer {get; set; } public DbSet<OrderInfo> OrderInfo{ get; set; } }
要能繼承DbContext類,就要添加System.Data.Entity,即引用在我們程式目錄下的packages\EntityFramework.5.0.0\lib\net40\EntityFramework.dll
下面來寫下設定檔
<?xmlversion="1.0" encoding="utf-8" ?><configuration> <connectionStrings> <add name="ConnCodeFirst"connectionString="server=.;uid=sa;pwd=1;database=CodeFirstDemoDb"providerName="System.Data.SqlClient"/> </connectionStrings></configuration>
要注意的是我們命名的字串變數一定要和資料庫上下文類中的變數名一致。
用戶端程式
class Program { static void Main(string[] args) { HotelDbContext dbcontext = newHotelDbContext(); dbcontext.Database.CreateIfNotExists();//如果資料庫不存在,建立資料庫 } }
執行,看看你的資料庫中有沒有添加成功吧!
後記
學習EF從代碼構建來實踐會有更加不一樣的體會,邏輯也更清晰了一些,三種構建方法我們都應該去實踐一下,這樣才能學好EF。
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。
Entity Framework之Code First