C#?LiteDB基本使用示例代碼
LiteDB 是一個(gè)小型、快速、輕量級的 .NET NoSQL 嵌入式數(shù)據(jù)庫,也就是我們常說的 K/V 數(shù)據(jù)庫,完全用 C# 托管代碼開發(fā),并且是免費(fèi)和開源的,Github Star 數(shù)近 7k。它非常適合在移動應(yīng)用 (Xamarin iOS/Android)和小型的桌面/Web 應(yīng)用中使用。
LiteDB 的靈感來自 MongoDB 數(shù)據(jù)庫,所以它的 API 和 MongoDB 的 .NET API 非常相似。
LiteDB是一種文檔型單文件數(shù)據(jù)庫,基于Key-Value方式存取數(shù)據(jù)。
LiteDB的基本數(shù)據(jù)結(jié)構(gòu)
BsonDocument
BsonDocument
用于存儲單一對象,其構(gòu)造函數(shù)接收字典型數(shù)據(jù),定義存儲的具體內(nèi)容。
BsonArray
BsonArray
用于存儲多項(xiàng)同類型對象,其構(gòu)造函數(shù)接收對象集合。
BsonValue
BsonValue
是BsonDocument
和BsonArray
的公共基類,可以在運(yùn)行時(shí)確定其具體類型,通過一系列As*
方法將其轉(zhuǎn)換為具體類型。
LiteDB基本使用
1.創(chuàng)建實(shí)體類
創(chuàng)建一個(gè)實(shí)體類
{ public int Id { get; set; } public int Age { get; set; } public string Name { get; set; } = string.Empty; public string[] Phone { get; set; } public bool IsActive { get; set; } }
2.連接數(shù)據(jù)庫以及一些CRUD
在NuGet中添加LiteDB
// 打開數(shù)據(jù)庫,如果不存在就會自動創(chuàng)建 var db = new LiteDatabase(@"MyData.db"); // 增刪改查案例 // 獲取Student集合對象 var col = db.GetCollection<Student>("student"); for(int i = 1; i < 10; i++) { var student = new Student() { Id = i, Age = 18+i, Name = "Test", Phone = new string[] { "8000-1000"+i, "1001-8080"+i }, IsActive = true, }; // 數(shù)據(jù)插入 col.Insert(student); } // 在id字段上創(chuàng)建唯一索引 col.EnsureIndex(x => x.Id, true); // 數(shù)據(jù)查詢 List<Student> list = col.Find(x => x.Age > 20).ToList(); Student user = col.FindOne(x => x.Id == 1); Console.WriteLine($"Lite數(shù)據(jù)庫中共有{list.Count}人年齡大于20的人"); foreach (Student stu in list) { ShowInfo(stu); } Console.WriteLine("Lite數(shù)據(jù)庫中Id為1的人"); ShowInfo(user); // 刪除所有數(shù)據(jù) col.DeleteAll(); } static void ShowInfo(Student student) { Console.WriteLine("姓名:"+student.Name + "年齡:"+student.Age); }
到此這篇關(guān)于C# LiteDB基本使用示例代碼的文章就介紹到這了,更多相關(guān)C# LiteDB使用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C#使用WebSocket與網(wǎng)頁實(shí)時(shí)通信的實(shí)現(xiàn)示例
本文主要介紹了C#使用WebSocket與網(wǎng)頁實(shí)時(shí)通信的實(shí)現(xiàn)示例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-08-08C#實(shí)現(xiàn)統(tǒng)計(jì)字?jǐn)?shù)功能的方法
這篇文章主要介紹了C#實(shí)現(xiàn)統(tǒng)計(jì)字?jǐn)?shù)功能的方法,較為詳細(xì)的分析了C#字?jǐn)?shù)統(tǒng)計(jì)功能的原理與實(shí)現(xiàn)技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-08-08解決C# winForm自定義鼠標(biāo)樣式的兩種實(shí)現(xiàn)方法詳解
本篇文章是對在C#中winForm自定義鼠標(biāo)樣式的兩種實(shí)現(xiàn)方法進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-05-05C#實(shí)現(xiàn)可緩存網(wǎng)頁到本地的反向代理工具實(shí)例
這篇文章主要介紹了C#實(shí)現(xiàn)可緩存網(wǎng)頁到本地的反向代理工具,實(shí)例分析了C#實(shí)現(xiàn)反向代理的相關(guān)技巧,非常具有實(shí)用價(jià)值,需要的朋友可以參考下2015-04-04