ASP.NET MVC 5 + EF 6 入門教程 (5) Model和Entity Framework

來源:互聯網
上載者:User

標籤:style   blog   http   ar   color   sp   on   檔案   資料   

文章來源: Slark.NET-部落格園 http://www.cnblogs.com/slark/p/mvc-5-ef-6-get-started-model.html 

上一節:ASP.NET MVC 5 入門教程 (4) View和ViewBag

源碼下載:點我下載

MVC中的Model是用來給View提供顯示資料的對象。

這裡我們首先建立一個Model對象。

在方案總管中右鍵點擊Models檔案夾,選擇添加->類。添加一個名為Employee.cs的Model類。Models檔案夾是預設存放所有Model的地方。

在Employee.cs檔案中添加如下代碼:

namespace SlarkInc.Models{    public class Employee    {        public int Id { get; set; }        public string Name { get; set; }        public int Age { get; set; }    }}

這樣我們就建立好了一個Model資料模型包含Id、Name、Age三個屬性。

為了持久化資料,我們這裡用Entity Framework。

Entity Framework (EF) 簡單點說就是.NET開發中的一種訪問資料庫的方法,其最大的特點就是能通過物件導向的方法訪問資料而不用寫sql語句。

我們用EF的Code First方法建立資料庫表。

Code First方法簡單點說就是第一步用C#建立一個實體類,第二步由這個類產生資料庫表。

第一步上面已經完成。第二步產生資料庫表之前要建立資料庫上下文。

將Employee.cs檔案中的代碼寫成如下形式:

using System.Data.Entity;namespace SlarkInc.Models{    public class Employee    {        public int Id { get; set; }        public string Name { get; set; }        public int Age { get; set; }    }    public class EmployeeDBContext : DbContext    {        public DbSet<Employee> Employees { get; set; }    }}

圖中黃色標記部分就是為EF持久化添加的代碼。

EmployeeDBContext類繼承自EF提供的DbContext。EmployeeDBContext代表Employee的資料庫上下文,負責處理資料的增刪改查操作。

public DbSet<Employee> Employees { get; set; }將C#的Employee類映射到資料庫的Employee表。

後面會介紹如何串連資料庫建立庫表添加資料,敬請期待。

您的留言和推薦是我寫作的動力,謝謝。

ASP.NET MVC 5 + EF 6 入門教程 (5) Model和Entity Framework

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.