C#LiteDB基本使用

LiteDB基本使用

1.创建实体类

创建一个实体类

{
    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.连接数据库以及一些CRUD

在NuGet中添加LiteDB

    // 打开数据库,如果不存在就会自动创建
    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, 
         };
        // 数据插入
        col.Insert(student);
    }
    // 在id字段上创建唯一索引
    col.EnsureIndex(x => x.Id, true);
    // 数据查询
    List<Student> list = col.Find(x => x.Age > 20).ToList();
    Student user = col.FindOne(x => x.Id == 1);
    Console.WriteLine($"Lite数据库中共有{list.Count}人年龄大于20的人");
    foreach (Student stu in list)
    {
        ShowInfo(stu);
    }
    Console.WriteLine("Lite数据库中Id为1的人");
    ShowInfo(user);

	// 删除所有数据
    col.DeleteAll();
}

static void ShowInfo(Student student)
{
    Console.WriteLine("姓名:"+student.Name + "年龄:"+student.Age);
}
  • 8
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值