ASP .NET MVC 之Entity Framework- code first

來源:互聯網
上載者:User

最近,用到了ASP.NET  MVC Entity Framework  開發了一些項目,感覺還是非常好用了,這讓我見證了微軟技術的發展:

-通過這個圖,我們很清晰的看到,資料訪問方式的改變。

如果,你想瞭解,ADO.NET Entity Framework, 你可以直接存取這個網站  Entity Framework

如果,你想瞭解ASP.NET MVC , 你可以直接存取這個網站:MVC

下面我介紹一下Entity Framework 的一些運用:

 

在園子裡,我看到很多關於MVC的講解,很多的用到的是Model First, or Schema First . 在這裡,我將結合ASP.NET
MVC 3.0 , 做一個Entity Framework CODE FIRST的示範,希望大家能有所協助。特別是,對你想架構小型項目的時候,這個運用是非常有協助的.

實驗環境:

OS: Windows Server 2008R2, Windows 7

DE: VS2010 + MVC 3.0+Entity Framework+ SQL Server 2008 R2

一、建立MVC
3.0的網站項目,這和大家建立其他的MVC項目是一樣的。注意:在建立之前,記得先安裝MVC 3.0, Entity Framework. 建立完之後,你將會看到經典的MVC 模式,Model->View->Control

二、在Model中添加2個類,一個是Restaurant,一個是OdeToFoodDB,
定義如下:

Restaurant

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MVCET.Models
{
    public class Restaurant
    {
        public int ID { get; set; }
        public string  Name { get; set; }
        public string State { get; set; }
        public Adress  Adress { get; set; }
          
    }
}

 

OdeToFoodDB

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;

namespace MVCET.Models
{
    public class OdeToFoodDB:DbContext
    {        
        public DbSet<Restaurant> Restaurants { get; set; }
        public DbSet<Reviewers> Reviewer { get; set; }
    }
}

OdeToFoodDB, 注意這個類必須繼承 DbContext

然後,在webConfig中添加一個資料庫連接字串,如下:

 <configuration>
  <connectionStrings>
    <add name="ApplicationServices"
         connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true"
         providerName="System.Data.SqlClient" />
    <add name="OdeToFoodDB"
         connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;initial catalog=OdeToFoodDB;"
    providerName="System.Data.SqlClient"/>
  </connectionStrings>

三、在Control 中添加RestaurantControl 類,再為Index()函數添加View. 並且選擇強型別去顯示資料。這時候,view 會自動綁上資料,顯示資料。這時候,肯定沒有資料,如果要有資料怎麼弄呢?這時候就到根據代碼產生資料庫。
四、在VS 中選擇伺服器瀏覽器視窗,在資料庫的節點上選擇"Add Connection …." 中文版的就是“添加新的串連”。寫上資料庫的伺服器名稱,在填上資料庫的名字,如所示: 

點擊ok,然後建立資料庫,如果,有對話方塊彈出來,選擇"Yes" 就行了。這時候,系統就會自動產生資料庫了,如所示

我們,看到Restaurants 表中的欄位和我們定義的Restaurant中欄位的名字基本類似的  
到現在為止,我們已經根據代碼結構產生了資料庫.但是,如果Restaurant 中的欄位有所改變,怎辦辦呢?這時候,就要到Drop以前的資料庫,然後,重現建立資料庫 
五、類發生了改變,資料庫也發生對應的改變:
在Global.asax 中的 Application_Start() 函數中,添加以下的代碼

protected void Application_Start()
        {
           // Database.SetInitializer(new DropCreateDatabaseIfModelChanges<OdeToFoodDB>()); 
            Database.SetInitializer(new OdeToFoodDBInitializer()); 
            AreaRegistration.RegisterAllAreas();

            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);
        }

你也可以寫一個類繼承DropCreateDatabaseIfModelChanges<OdeToFoodDB>, 如下代碼所示,你就可以不用注釋的哪一行代碼了

OdeToFoodDBInitializer

public class OdeToFoodDBInitializer :
        DropCreateDatabaseIfModelChanges<OdeToFoodDB>
    {
        protected override void Seed(OdeToFoodDB context)
        {
            base.Seed(context);

            context.Restaurants.Add(
                new Restaurant()
                {
                    Name = "qitian",
                    Adress = new Adress() { Street = " Nanjiang RD, MD", City = "Shanghai" }
                });

            context.Restaurants.Add(
                new Restaurant()
                {
                    Name = "haiyun",
                    Adress = new Adress() { Street = " Dongchuan RD, MD", City = "Shanghai" }
                });
            context.Restaurants.Add(
                new Restaurant()
                {
                    Name = "qitian",
                    Adress = new Adress() { Street = " Beijing RD, HF", City = "Guangdong" }
                });

            context.Restaurants.Add(
                new Restaurant()
                {
                    Name = "Lantian",
                    Adress = new Adress() { Street = " Wuhan RD, HF", City = "Guangdong" }
                });

            context.Reviewer.Add(new Reviewers() { 
            Name="Tomin", Sex="Female"});
            context.Reviewer.Add(new Reviewers()
            {
              
                Name = "Tony",
                Sex = "Male"
            });

            context.SaveChanges();
                
        }
    }

重新運行運用程式,會給你一個意想不到的結果,你會驚呆的。

MVCET.zip

 

相關文章

聯繫我們

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