EntityFramework Code-First 簡易教程(三)-------資料庫初始化

來源:互聯網
上載者:User

標籤:

現在我們來學習,當資料庫初始化的時候,Code First怎樣設定資料庫的名字。

下面的圖顯示了資料庫初始化的工作流程,根據傳入給context基類的建構函式的參數來初始化:

根據上面的圖,context基類的建構函式可以傳入如下參數:

  1. 無參數
  2. 參數為資料庫名稱
  3. 參數為連接字串
 無參數的建構函式:

如果不傳參數給context基類的建構函式,它就會在我們本地建立一個以{命名空間}.{Context類名}為名字的資料庫。比如下面代碼會建立一個名字為SchoolDataLayer.Context的資料庫

namespace SchoolDataLayer{    public class Context: DbContext     {        public Context(): base()        {                    }    }}

 

傳入資料庫名稱的建構函式:

我們也可以指定一個資料庫名稱作為參數傳入給context的建構函式,這樣在本地就會給我們建立一個以傳入參數為名稱的資料庫。如下面的代碼,會建立一個名稱為MySchoolDB的資料庫

namespace SchoolDataLayer{    public class Context: DbContext     {        public Context(): base("MySchoolDB")         {                           }    }}

 

傳入連接字串的建構函式:

我們在app.config或web.config裡定義了連接字串之後,就也可以用“name=”+連接字串 這種格式作為參數傳給context的建構函式。如下面的代碼,我們傳入了name=SchoolDBConnectionString給context的建構函式

namespace SchoolDataLayer{    public class Context: DbContext     {        public SchoolDBContext() : base("name=SchoolDBConnectionString")         {        }    }}

 

App.config:

<?xml version="1.0" encoding="utf-8" ?><configuration>    <connectionStrings>    <add name="SchoolDBConnectionString"     connectionString="Data Source=.;Initial Catalog=SchoolDB-ByConnectionString;Integrated Security=true"     providerName="System.Data.SqlClient"/>    </connectionStrings></configuration>

在上面的context類裡,我們把連接字串傳入它的建構函式,請注意,連接字串名必須以“name=”開頭,否則,Code-First會把它當做資料庫名。因為在app.config裡的連接字串的資料庫名稱是SchoolDB-ByConnectionString,所以Code-First會建立一個以SchoolDB-ByConnectionString命名的資料庫或者使用已存在的同名資料庫。對了,還要確保app.config裡的連接字串包含providerName = "System.Data.SqlClient"屬性。

 

總結:Code-First使用傳入給基類建構函式的不同參數來初始化資料庫。

 

EntityFramework 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.