LiteDB介绍
LiteDB 是一个小巧、快速和轻量级的 .NET NoSQL 嵌入式数据库。
- 无服务器的 NoSQL 文档存储
- 简单的 API,类似于 MongoDB
- 100% 的 C# 代码支持 .NET 4.5 / NETStandard 1.3/2.0,以单个 DLL(不到 450KB)形式提供
- 线程安全
- 支持 ACID,完整的事务支持
- 写入失败后的数据恢复(WAL 日志文件)
- 使用 DES(AES)加密算法对数据文件进行加密
- 使用属性或流畅的映射器 API 将 POCO 类映射为 BsonDocument
- 存储文件和流数据(类似于 MongoDB 的 GridFS)
- 单一数据文件存储(类似于 SQLite)
- 对文档字段建立索引以实现快速搜索
- 支持 LINQ 查询
- 提供类似于 SQL 的命令来访问/转换数据
- LiteDB Studio - 数据访问的精美用户界面
- 开源且免费供所有人使用,包括商业用途
nuget安装
dotnet add package LiteDB --version 5.0.21
BsonRef定义关联关系
using LiteDB;
namespace LiteDBAPI.Models
{
public class Customer:BaseClass
{
[BsonField("customername")]
public string Name { get; set; }
}
public class Order: BaseClass
{
[BsonField("price")]
public double Price { get; set; }
[BsonRef("customers")]
public Customer Customer { get; set; }
}
public class BaseClass
{
[BsonId]
public ObjectId ID { get; set; }
}
}
封装helper
using LiteDB;
using LiteDBAPI.Models;
using System.Linq.Expressions;
namespace LiteDBAPI
{
public class LiteDBHelper
{
public readonly LiteDatabase db;
public LiteDBHelper()
{
db = new LiteDatabase("Filename=database.db;Password=1234;Connection=shared");
}
public BsonValue insert<T>(T value,string collectionName)
{
// Get a collection (or create, if doesn't exist)
var col = db.GetCollection<T>(collectionName);
// Insert new customer document (Id will be auto-incremented)
return col.Insert(value);
}
public T getOrder<T, TRelated>(string orderid,string collectionName, Expression<Func<T, TRelated>> includeExpression) where T : BaseClass
{
ObjectId objectId = new ObjectId(orderid);
var col = db.GetCollection<T>(collectionName);
return col.Query().Where(x =>x.ID== objectId).Include(includeExpression).FirstOrDefault();
}
public bool update<T>(T instance,string collectionName)
{
var col = db.GetCollection<T>(collectionName);
return col.Update(instance);
}
public List<T> queryByCondition<T>(string collectionName,Dictionary<string,string> keyValuePairs)
{
var col = db.GetCollection<T>(collectionName);
// Create a list to hold individual query expressions
var queryList = new List<BsonExpression>();
BsonExpression? combinedQuery = null;
// Loop through the key-value pairs and create equality conditions
foreach (var pair in keyValuePairs)
{
PropertyInfo propertyType = typeof(T).GetProperty(pair.Key);
BsonFieldAttribute attr = (BsonFieldAttribute)propertyType.GetCustomAttributes(typeof(BsonFieldAttribute),false).FirstOrDefault();
object? value = Convert.ChangeType(pair.Value, propertyType.PropertyType);
queryList.Add(Query.EQ(attr.Name, new BsonValue(value)));
}
if (queryList.Count>1)
{
// Combine the individual conditions into an AND query
combinedQuery = Query.And(queryList.ToArray());
}
else
{
combinedQuery = queryList[0];
}
// Execute the query and return the results as a list
return col.Find(combinedQuery).ToList();
}
}
}
controller使用
using LiteDB;
using LiteDBAPI.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace LiteDBAPI.Controllers
{
[Route("api/[controller]/[action]")]
[ApiController]
public class LiteDBController : ControllerBase
{
private readonly LiteDBHelper db;
public LiteDBController(LiteDBHelper db)
{
this.db = db;
}
[HttpPost]
public IActionResult insert([FromBody] string customername)
{
Customer customer = new Customer() { Name = customername };
// customer
this.db.insert(customer, "customers");
// order
this.db.insert(new Order() { Customer=customer }, "orders");
return Ok(new { result="success"});
}
[HttpGet]
public Order getOrder([FromQuery] string orderid)
{
return db.getOrder<Order,Customer>(orderid,"orders",x=>x.Customer);
}
[HttpPut]
public IActionResult updatePrice([FromQuery] string orderid)
{
Order order = db.getOrder<Order, Customer>(orderid, "orders", x => x.Customer);
order.Price =order.Price + 100;
return Ok(db.update<Order>(order, "orders"));
}
[HttpPost]
public List<Customer> getCustomer([FromBody] Dictionary<string,string> keyValuePairs)
{
return db.queryByCondition<Customer>("customers",keyValuePairs);
}
}
}
加密
通过更改连接参数,添加password实现