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);
}
相关推荐
RobinDevNotes6 小时前
一套代码发布到十几个平台:Cocos入门速览
typescript·c#·游戏开发
阿松爱学习8 小时前
【Unity开发】监听Scene场景事件
unity·c#
天天代码码天天17 小时前
屏幕翻拍满是彩色条纹?用 C# + Vulkan 做了一个去摩尔纹工具,支持单图与文件夹批量
c#·去摩尔纹
2501_9307077817 小时前
使用C#代码在 Word 文档中添加、插入或删除页面
开发语言·c#·word
淡海水19 小时前
03-03-架构篇-SGen GC架构解析
unity·架构·c#·gc·sgen
曹牧1 天前
C#:输入的字符串格式不正确
c#
根号五2 天前
JetBrains Rider 使用教程(1)新建解决方案
c#·jetbrains rider
海天鹰2 天前
C#:接收从打开方式打开的参数
c#
宝桥南山2 天前
.NET 11 - 尝试一下Minimal API中的异步验证新特性
microsoft·微软·c#·asp.net·.net·.netcore
开开心心_Every2 天前
文件查重软件批量删除重复文件释放空间
java·开发语言·c#·计算机外设·ocr·excel·perl