C#LiteDB基本使用

C#LiteDB基本使用

LiteDB基本使用

1.创建实体类

创建一个实体类

public 复制代码
{
    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);
}
相关推荐
HH牛码2 小时前
C# 中 Array、ArrayList 和 List 的比较
开发语言·c#
HH牛码2 小时前
C#学生管理系统 进阶(通过接口,继承接口的类,实现接口约束_对List中存储的数据进行排列)
c#
吾与谁归in3 小时前
C#实现本地Deepseek模型及其他模型的对话
人工智能·c#·wpf·deepseek
子蛟7 小时前
Get a free SSL certificate interface.
c#·ssl
一只蜗牛儿11 小时前
C# 版 OpenCV:OpenCVSharp 最详细最全面教程(万字详细总结)
开发语言·opencv·c#
学海无涯,行者无疆11 小时前
使用Jenkins实现Windows服务器下C#应用程序发布
windows·c#·jenkins·.net·cicd·自动发布·一键发布
tnnnnt13 小时前
今天锐评一下C#
开发语言·c#
Sator114 小时前
C#与AI的交互(以DeepSeek为例)
ai·语言模型·c#
玩c#的小杜同学16 小时前
从“Switch-case“到“智能模式“:C#模式匹配的终极进化指南
开发语言·前端·c#·.net
步、步、为营18 小时前
解锁C# XML编程:从新手到实战高手的蜕变之路
xml·数据库·c#