=========================简单使用=================
// 创建你的 POCO 类
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; }
}
// 打开数据库 (如果不存在则创建)
using(var db = new LiteDatabase(@"MyData.db"))
{
// 获得 customer 集合
var col = db.GetCollection<Customer>("customers");
// 创建你的新 customer 实例
var customer = new Customer
{
Name = "John Doe",
Phones = new string[] { "8000-0000", "9000-0000" },
Age = 39,
IsActive = true };
// 在 Name 字段上创建唯一索引
col.EnsureIndex(x => x.Name, true);
// 插入新的 customer 文档 (Id 是自增的)
col.Insert(customer);
// 更新集合中的一个文档
customer.Name = "Joana Doe";
col.Update(customer);
// 使用 LINQ 查询文档 (未使用索引)
var results = col.Find(x => x.Age > 20);
}
======================使用 fluent 映射器和跨文档引用处理更复杂的数据模型======================
// DbRef 交叉引用
public class Order{
public ObjectId Id { get; set; }
public DateTime OrderDate { get; set; }
public Address ShippingAddress { get; set; }
public Customer Customer { get; set; }
public List<Product> Products { get; set; }
}
// 重用全局实例的映射器
var mapper = BsonMapper.Global;
// "Produts" 和 "Customer" 来自其他集合 (而不是嵌入的文档)
mapper.Entity<Order>()
.DbRef(x => x.Customer, "customers") // 1 对 1/0 引用
.DbRef(x => x.Products, "products") // 1 对多引用
.Field(x => x.ShippingAddress, "addr");
// 嵌入的子文档
using(var db = new LiteDatabase("MyOrderDatafile.db"))
{
var orders = db.GetCollection<Order>("orders");
// 当查询 Order 时,包含引用
var query = orders
.Include(x => x.Customer)
.Include(x => x.Products) // 1 对多引用
.Find(x => x.OrderDate <= DateTime.Now);
// 每个 Order 实例都会加载 Customer/Products 引用
foreach(var order in query)
{
var name = order.Customer.Name;
...
}
}
===========================================