如何在 ASP.NET MVC下使用 Sqlite (ASP.NET MVC 5 With Sqlite)


  1. Env Setup Steps
    1. Install Toolbox
    2. Install SQLite in GAC
    3. Nuget Install System.Data.SQLite
    4. Setting Web.config
  2. Dev Steps
  3. 常見錯誤
    1. Unable to open the database file
    2. 無法寫入檔案
    3. 載入資料庫時無法轉型
  4. 參考資料

Sqlite 的方便用過都知道,如何在 ASP.NET MVC 下順利地使用呢?幾項步驟,跟著完成就可以使用!

Env Setup Steps

  1. Update Visual Studio 2017 (version >= 15.8 )
  2. Install Toolbox
  3. Install SQLite in GAC
  4. Nuget Install System.Data.SQLite
  5. Setting Web.config

Install Toolbox

藉由 擴充功能和更新 尋找 SQLite Compact Toolbox 後安裝。

Install SQLite in GAC

安裝版本:sqlite-netFx46-setup-bundle-x86-2015-1.0.110.0

安裝時要一併勾選下列選項,否則在使用 EntityFramework 時會出現未安裝正確的 Provider:

記得勾選相關選項

System.Data.SQLite Downloads Page

Nuget Install System.Data.SQLite

藉由 Nuget 搜尋 System.Data.SQLite 後安裝。

⚠️ 絕對務必千萬要裝 System.Data.SQLite
不要自作主張裝 sqliteMicrosoft.Data.Sqlite,否則人生將會消失一個小時在尋找SQLite Provider (simple for ES6 by ErikEJ)。

⚠️ 要注意 Nuget 安裝的軟體版本必須要小於等於上一步驟 GAC 安裝的版本,否則 EntityFramework 載入資料庫可能發現無法轉型的錯誤。

System.Data.SQLite

Setting Web.config

於 Web.config 之 configuration > entityFramework > providers 加入:

<provider 
  invariantName="System.Data.SQLite" 
  type="System.Data.SQLite.EF6.SQLiteProviderServices, System.Data.SQLite.EF6" 
/>

以上完成專案環境設定步驟

Dev Steps

  1. 確認 sqlite 檔案 (.db) 儲存於 App_Data folder
  2. Models Folder 加入新增項目 ADO.NET實體資料模型

ADO.NET實體資料模型

  1. 選擇 來自資料庫的EF Designer

來自資料庫的EF Designer

  1. 新增連結,資料連結選擇 SQLite Provider (simple for ES6 by ErikEJ)

SQLite Provider (simple for ES6 by ErikEJ)

  1. Connection String 輸入 (記得包含 data source = )
    開發環境data source = C:\ProjectName\App_Data\datas.db
    正式環境data source = |DataDirectory|\datas.db
  2. 新增 Controller Scaffolding
  3. 選擇 Controller folder right click 新增 > 控制器 並選擇 具有檢視、使用 Entity Framework 的 MVC5 控制器
  4. 選擇模型類別及資料內容類別
  5. 編譯完成後驗證結果
  6. 在 Web.Release.config 加入 對應之 ConnectionName 與 |DataDirectory|\data.db
  7. 於部署端資料夾設定存取權限
<?xml version="1.0" encoding="utf-8"?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
  <connectionStrings>
    <add name="ConnectionName"
      connectionString="metadata=res://*/Models.GenericContent.csdl|res://*/Models.GenericContent.ssdl|res://*/Models.GenericContent.msl;provider=System.Data.SQLite.EF6;provider connection string='data source=&quot;|DataDirectory|\data.db&quot;'"
      xdt:Transform="SetAttributes" xdt:Locator="Match(name)"/>
  </connectionStrings>
</configuration>

常見錯誤

Unable to open the database file

Connection String 沒有正確設定為 data source = |DataDirectory|\datas.db

無法寫入檔案

資料夾的權限設定不足

載入資料庫時無法轉型

檢查 GAC 與 System.Data.SQLite 的版本是否一致。

轉型錯誤,需要安裝新版的 GAC

參考資料

EF6 workflow with SQLite DDEX provider

在 vs2017 中使用 Entity Framework 操作 SQLite

DB Browser For SQLite