ASP.NET MVC——CodeFirst開發模式

來源:互聯網
上載者:User

標籤:

    Entity Framework架構提供了幾種開發模式,比如Database First,Model First,Code First。Database First是最老也是應用得最廣泛的一種設計方式。Database First這種方式的設計高度依賴於資料庫中表的結構,根據表及表間的關係來建立模型。如果後期需求有所變更或者功能有很大變化的話,需要涉及到更改資料庫所付出的代價將會很大,因為之前編寫好的代碼將不再適用於新的表,我們必需重構以更改代碼中的邏輯以適應更改之後的表。Model Firstj是建立ADO.NET實體物件以及它們之間的關係,然後再指定到資料庫的映射。這個實體物件即為Model。

    我們今天要講的是Code First(代碼先行)。它思想就是先定義模型中的類,再通過這些類產生資料庫。這種開發模式適合於全新的項目,它使得我們可以以代碼為核心進行設計而不是先構造資料庫。

    接下來我就以一個簡單的例子來介紹這種開發模式。我們的需求是兩個表,部落格表和評論表。一個部落格對應多個評論,一個評論對應一個部落格。這是一對多關聯性。我們先建立一個ASP.NET MVC項目,並用NuGet安裝EntityFramework。

    public class Blog    {        [Key]        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]        public Guid Id { get; set; }        public string Title { get; set; }        public string Author { get; set; }        public DateTime Time { get; set; }        public string Summary { get; set; }        public string Content { get; set; }        public virtual ICollection<Comment> Comments { get; set; } = new List<Comment>();    }
    public class Comment    {        [Key]        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]        public Guid Id { get; set; }        public string VisitorName { get; set; }        public string Email { get; set; }        public DateTime Time { get; set; }        public string Content { get; set; }        [ForeignKey("Blog")]        public Guid BlogId { get; set; }        public virtual Blog Blog { get; set; }    }

    接下來我們建立資料內容。建立一個檔案夾叫Context,並在其中建立類,代碼如下:

    public class EFDbContext : DbContext    {        public DbSet<Blog> Blogs { get; set; }        public DbSet<Comment> Comments { get; set; }        protected override void OnModelCreating(DbModelBuilder modelBuilder)        {            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();  //去除“設定表名為複數”這條約定        }    }

    接著我們在Web.config中來設定資料庫,我們使用輕量級的LocalDB。在Web.config中的<configuration>節點中加入如下配置

  <connectionStrings>    <add name="EFDbContext" connectionString="Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=Blog;Integrated Security=True" providerName="System.Data.SqlClient" />  </connectionStrings>

    接下來,我們建立一個控制器,選擇“包含視圖的MVC5控制器(使用Entity Framework)”,模型類選擇Blog,資料內容類選擇EFDbContext(這裡需要預先編譯一下才能看到),控制器名稱為HomeController,點擊添加,我們便有了具有CRUD功能的Controller和View。

    我們運行項目,就可以進行CRUD操作了。然後我們結束調試,開啟伺服器總管,在資料連線那裡就可以看到我們利用代碼產生的資料庫表。

    最後,我們來講講表與表之間的關係。有三種,一對一關聯性,一對多關聯性,多對多關係。主要在導覽屬性裡進行配置,比如前面的blog表和comment表,我們在類裡面加了這樣的代碼。

public virtual ICollection<Comment> Comments { get; set; } = new List<Comment>(); //一個blog對應多個comment
public virtual Blog Blog { get; set; } //一個comment對應一個blog

    多對多關係我們便需要藉助第三張表來連結。

ASP.NET MVC——CodeFirst開發模式

聯繫我們

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