Entity Framework之Code First

來源:互聯網
上載者:User

標籤: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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.