C#?LiteDB基本使用示例代碼
LiteDB 是一個小型、快速、輕量級的 .NET NoSQL 嵌入式數(shù)據(jù)庫,也就是我們常說的 K/V 數(shù)據(jù)庫,完全用 C# 托管代碼開發(fā),并且是免費和開源的,Github Star 數(shù)近 7k。它非常適合在移動應用 (Xamarin iOS/Android)和小型的桌面/Web 應用中使用。
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
用于存儲多項同類型對象,其構(gòu)造函數(shù)接收對象集合。
BsonValue
BsonValue
是BsonDocument
和BsonArray
的公共基類,可以在運行時確定其具體類型,通過一系列As*
方法將其轉(zhuǎn)換為具體類型。
LiteDB基本使用
1.創(chuàng)建實體類
創(chuàng)建一個實體類
{ 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); }
到此這篇關于C# LiteDB基本使用示例代碼的文章就介紹到這了,更多相關C# LiteDB使用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
C#使用WebSocket與網(wǎng)頁實時通信的實現(xiàn)示例
本文主要介紹了C#使用WebSocket與網(wǎng)頁實時通信的實現(xiàn)示例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2022-08-08C#實現(xiàn)統(tǒng)計字數(shù)功能的方法
這篇文章主要介紹了C#實現(xiàn)統(tǒng)計字數(shù)功能的方法,較為詳細的分析了C#字數(shù)統(tǒng)計功能的原理與實現(xiàn)技巧,具有一定參考借鑒價值,需要的朋友可以參考下2015-08-08解決C# winForm自定義鼠標樣式的兩種實現(xiàn)方法詳解
本篇文章是對在C#中winForm自定義鼠標樣式的兩種實現(xiàn)方法進行了詳細的分析介紹,需要的朋友參考下2013-05-05C#實現(xiàn)可緩存網(wǎng)頁到本地的反向代理工具實例
這篇文章主要介紹了C#實現(xiàn)可緩存網(wǎng)頁到本地的反向代理工具,實例分析了C#實現(xiàn)反向代理的相關技巧,非常具有實用價值,需要的朋友可以參考下2015-04-04