天天看點

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。

繼續閱讀