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);
}
相关推荐
GISer_Qing3 小时前
ASP.NET Core 8.0学习笔记(二十七)——数据迁移:Migrations深入与其他迁移命令
数据库·c#·.netcore·entityframework
追烽少年x4 小时前
C# WinForm 中的事件驱动模型
c#
CE贝多芬5 小时前
WPF的页面设计和实用功能实现
c#·wpf
code_shenbing6 小时前
WPF 实现虚拟键盘
c#·wpf
软件黑马王子11 小时前
C#初级教程(4)——流程控制:从基础到实践
开发语言·c#
水煮庄周鱼鱼16 小时前
C# 入门简介
开发语言·c#
软件黑马王子17 小时前
Unity游戏制作中的C#基础(6)方法和类的知识点深度剖析
开发语言·游戏·unity·c#
Nicole Potter18 小时前
请说明C#中的List是如何扩容的?
开发语言·面试·c#
gu2019 小时前
c#编程:学习Linq,重几个简单示例开始
开发语言·学习·c#·linq
pchmi1 天前
CNN常用卷积核
深度学习·神经网络·机器学习·cnn·c#