C# Linq To Sqlite (Linq to SQL)


  1. 說明

筆記如何使用 Linq 讀取 Sqlite 的資料。

logo

說明

要使用的技術為 Linq to Sql,這是一個已經逐漸 Deprecated 的資料庫存取技術,本次主要示範如何藉由其簡易地存取 Sqlite。

而本次所使用的 sqlite 檔案為 Northwind sqlite 版本,由 jpwhite3 / northwind-SQLite3 取得。


首先需要使用 nuget 安裝 System.Data.SQLite,會一併安裝 System.Data.SQLite.EF6 以及 System.Data.SQLite.Linq

System.Data.Linq
System.Data.SQLite
System.Data.SQLite.EF6
System.Data.SQLite.Linq

要使用 LINQ 查詢 SQLite 資料,首先需要在專案中安裝 System.Data.SQLite 套件,然後使用 using System.Data.SQLite; 引用。

Controllers\HomeController.cs

using System.Data.SQLite;
using System.Data.Linq;

public ActionResult SQLite()
{
    using (var connection = new SQLiteConnection("Data Source=|DataDirectory|\\northwind.db"))
    {
        var context = new DataContext(connection);
        var results = context.GetTable<Dtos.Customer>().Where(c => c.City == "London");

        return View(results.ToList());
    }
}

為了讓 context.GetTable<Dtos.Customer> 可以正確對應,必須建立類別與 Sqlite 的資料表進行對應 (這邊是直接用 Entity Framework 所產生的類別加以修改),必須加入 Table 以及 Column 的 Attribute 來達成正確的對應。

\Dtos\Customer.cs

using System.Data.Linq.Mapping;

namespace NorthwindShop.Web.Dtos
{
    [Table(Name = "Customers")]
    public class Customer
    {
        [Column(IsPrimaryKey = true, IsDbGenerated = true)]
        public string CustomerID { get; set; }
        [Column]
        public string CompanyName { get; set; }
        [Column]
        public string ContactName { get; set; }
        [Column]
        public string ContactTitle { get; set; }
        [Column]
        public string Address { get; set; }
        [Column]
        public string City { get; set; }
        [Column]
        public string Region { get; set; }
        [Column]
        public string PostalCode { get; set; }
        [Column]
        public string Country { get; set; }
        [Column]
        public string Phone { get; set; }
        [Column]
        public string Fax { get; set; }
    }
}

完成設定後,經由 Action 的處理,即可在 View 中如期呈現:

Views\Home\SQLite.cshtml

@model IEnumerable<NorthwindShop.Web.Dtos.Customer>

@{
    ViewBag.Title = "SQLite";
}

<h2>SQLite</h2>

<table class="table table-bordered table-striped">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.CompanyName)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.ContactName)
        </th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.CompanyName)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.ContactName)
        </td>
    </tr>
}

</table>