使用LiteDB

LiteDB是一個簡單且快速的NoSQL Database,它特色有

  • 輕巧,< 450kb並且完全由.NET C#受控程式碼(managed code)編寫
  • 可以使用NuGet套件管理器安裝
  • 跨平台
  • 單一存放檔案
  • 支援LINQ query

以下是簡易的使用方式

  1. 使用NuGet管理套件搜尋LiteDB並安裝
  2. 接下來便可以使用LiteDatabase建立或是開啟database
1
2
3
4
5
6
string dbPath = @"./MyData.db";

// Open database (or create if doesn't exist)
using (var db = new LiteDatabase(dbPath)){
...
}
  1. 建立一個POCO class
1
2
3
4
5
6
7
8
9
public class Customer
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public string[] Phones { get; set; }
public bool IsActive { get; set; }
}

  1. 使用 db.GetCollection<Customer>("customers") 去取得customer collection
  2. collection的Insert方法插入資料

以下是完整的例子(來自LiteDB)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
string dbPath = @"./MyData.db";

// Open database (or create if doesn't exist)
using (var db = new LiteDatabase(dbPath))
{
// Get customer collection
var col = db.GetCollection<Customer>("customers");

// Create your new customer instance
var customer = new Customer
{
Name = "John Doe",
Phones = new string[] { "8000-0000", "9000-0000" },
Age = 39,
IsActive = true
};

// Create unique index in Name field
col.EnsureIndex(x => x.Name, true);

// Insert new customer document (Id will be auto-incremented)
col.Insert(customer);

// Update a document inside a collection
customer.Name = "123John Doe212";

col.Update(customer);

// Use LINQ to query documents (with no index)
var results = col.Find(x => x.Age > 20);
}

以下是方便你操作DB的GUI介面工具

  • OneBella:跨平台的GUI工具,支援修改和查詢,需要LiteDB 5+
    • 使用方式非常簡單,進入OneBella的 Release選擇下載對應平台的zip檔案即可
  • LiteDB.Studio
    • 一樣去Release下載最新版本即可,目前似乎只有Windows版本。