首页 > 其他分享 >LiteDb

LiteDb

时间:2024-06-11 19:32:42浏览次数:23  
标签:liteFileInfo db storage LiteDb var public

目录


本文记录LiteDb的使用,建议初学者使用时先根据官方的文档进行学习。

LookDown LiteDb官网

LookDown LiteDb Doc

LookDown LiteDb Package

LookDownLiteDb API

封装的代码

LiteDbWrapper.cs

    /// <summary>
    /// 官网:http://www.litedb.org/
    /// GitHub:https://github.com/mbdavid?tab=repositories
    /// GitHub:https://github.com/mbdavid/LiteDB
    /// LiteDB连接字符串:http://www.litedb.org/docs/connection-string/
    /// http://www.litedb.org/docs/getting-started/
    /// </summary>
    public partial class LiteDbWrapper : IDisposable
    {
        /// <summary>
        /// 数据库文件名称
        /// </summary>
        public string FilePath
        {
            get;
            private set;
        }
        private LiteDatabase _liteDb;
        /// <summary>
        /// LiteDb数据库
        /// </summary>
        public LiteDatabase LiteDb
        {
            get
            {
                return this._liteDb;
            }
            private set
            {
                this._liteDb = value;
            }
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="dbFilePath">数据库文件路径或连接字符串</param>
        /// <param name="autoInit">是否自动初始化,默认false</param>
        public LiteDbWrapper(string dbFilePath, bool autoInit = false)
        {
            this.FilePath = dbFilePath;

            if (autoInit)
            {
                this.InitialDb();
            }
        }

        /// <summary>
        /// 初始化LiteDB
        /// </summary>
        public virtual void InitialDb()
        {
            if (string.IsNullOrEmpty(this.FilePath))
            {
                throw new ArgumentNullException(nameof(this.FilePath));
            }

            if (null == this.LiteDb)
            {
                this.LiteDb = new LiteDatabase(this.FilePath);
            }
        }

        /// <summary>
        /// 执行数据库操作
        /// </summary>
        /// <param name="action"></param>
        public virtual void Do(Action<LiteDatabase> action)
        {
            if (null != this.LiteDb)
            {
                // 长连接
                action?.Invoke(this.LiteDb);
            }
            else
            {
                // 短连接
                using (var db = new LiteDatabase(this.FilePath))
                {
                    action?.Invoke(db);
                }
            }
        }
        /// <summary>
        /// 执行数组对象的操作
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="action"></param>
        /// <param name="name">Collection name (case insensitive)</param>
        public virtual void Do<T>(Action<ILiteCollection<T>> action, string name = null)
        {
            if (null != this.LiteDb)
            {
                // 长连接
                var col = this.LiteDb.GetCollection<T>(name);
                action?.Invoke(col);
            }
            else
            {
                // 短连接
                using (var db = new LiteDatabase(this.FilePath))
                {
                    var col = db.GetCollection<T>(name);
                    action?.Invoke(col);
                }
            }
        }

        /// <summary>
        /// 释放资源
        /// </summary>
        public virtual void Dispose()
        {
            if ((null != this.LiteDb))
            {
                this.LiteDb.Dispose();
            }
        }
    }

    public static class LiteDbExtensions
    {
        /// <summary>
        /// 根据Id存储文件,如果文件存在则更新
        /// </summary>
        /// <typeparam name="TFileId"></typeparam>
        /// <param name="db"></param>
        /// <param name="id"></param>
        /// <param name="filePath"></param>
        /// <param name="metaData"></param>
        /// <returns></returns>
        public static LiteFileInfo<TFileId> UploadFile<TFileId>(this LiteDatabase db, TFileId id, string filePath, BsonDocument metaData = null)
        {
            // Get file storage with Int Id
            var storage = db.GetStorage<TFileId>();

            // Upload a file from file system to database
            var liteFileInfo = storage.Upload(id, filePath);

            if ((null != liteFileInfo) && (null != metaData))
            {
                if (storage.Exists(liteFileInfo.Id))
                {
                    storage.SetMetadata(liteFileInfo.Id, metaData);
                }
            }

            return storage.FindById(liteFileInfo.Id);
        }
        /// <summary>
        /// 根据Id存储文件,如果文件存在则更新
        /// </summary>
        /// <typeparam name="TFileId"></typeparam>
        /// <param name="db"></param>
        /// <param name="id"></param>
        /// <param name="fileName"></param>
        /// <param name="stream"></param>
        /// <param name="metaData"></param>
        /// <returns></returns>
        public static LiteFileInfo<TFileId> UploadFile<TFileId>(this LiteDatabase db, TFileId id, string fileName, Stream stream, BsonDocument metaData = null)
        {
            // Get file storage with Int Id
            var storage = db.GetStorage<TFileId>();

            // Upload a file from Stream
            var liteFileInfo = storage.Upload(id, fileName, stream, metaData);
            return liteFileInfo;
        }

        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="db"></param>
        /// <param name="id"></param>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static LiteFileInfo<TFileId> DownloadFile<TFileId>(this LiteDatabase db, TFileId id, string filePath)
        {
            // Get file storage with Int Id
            var storage = db.GetStorage<TFileId>();

            // And download later
            var liteFileInfo = storage.Download(id, filePath, true);

            return liteFileInfo;
        }
        /// <summary>
        /// 下载文件
        /// </summary>
        /// <typeparam name="TFileId"></typeparam>
        /// <param name="db"></param>
        /// <param name="id"></param>
        /// <param name="stream"></param>
        /// <returns></returns>
        public static LiteFileInfo<TFileId> DownloadFile<TFileId>(this LiteDatabase db, TFileId id, Stream stream)
        {
            // Get file storage with Int Id
            var storage = db.GetStorage<TFileId>();

            // And download later
            var liteFileInfo = storage.Download(id, stream);

            return liteFileInfo;
        }
        /// <summary>
        /// 删除文件
        /// </summary>
        /// <typeparam name="TFileId"></typeparam>
        /// <param name="db"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public static bool DeleteFile<TFileId>(this LiteDatabase db, TFileId id)
        {
            // Get file storage with Id
            var storage = db.GetStorage<TFileId>();

            // And delete file, return true if success, false if not found
            return storage.Delete(id);
        }
    }
RegisterTypeManager.cs

    /// <summary>
    /// 自定义注册类型接口
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public interface IRegisterType<T>
    {
        /// <summary>
        /// 注册
        /// </summary>
        void RegisterType();
        /// <summary>
        /// 序列化
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        BsonValue Serialize(T entity);
        /// <summary>
        /// 反序列化
        /// </summary>
        /// <param name="bsonValue"></param>
        /// <returns></returns>
        T Deserialize(BsonValue bsonValue);
    }

    public abstract class RegisterTypeBase<T> : IRegisterType<T>
    {
        /// <summary>
        /// 注册
        /// </summary>
        public void RegisterType() => BsonMapper.Global.RegisterType<T>(Serialize, Deserialize);
        /// <summary>
        /// 序列化
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public abstract BsonValue Serialize(T entity);
        /// <summary>
        /// 反序列化
        /// </summary>
        /// <param name="bsonValue"></param>
        /// <returns></returns>
        public abstract T Deserialize(BsonValue bsonValue);
    }

    public static class RegisterTypeManager
    {
        public static void RegisterType<T>(RegisterTypeBase<T> registerType)
        {
            registerType.RegisterType();
        }
    }

    public class PointMapper : RegisterTypeBase<Point>
    {
        public override Point Deserialize(BsonValue bsonValue)
        {
            var x = bsonValue["X"].AsInt32;
            var y = bsonValue["Y"].AsInt32;
            return new Point(x, y);
        }

        public override BsonValue Serialize(Point entity)
        {
            return new BsonDocument(new Dictionary<string, BsonValue>
            {
            {"X", entity.X},
            {"Y", entity.Y},
            });
        }
    }
	....
    ....
    ....
    ....
    // 注册自定义序列化/反序列化器
    RegisterTypeManager.RegisterType(new PointMapper());

相关参考

  1. LiteDB用法小结

标签:liteFileInfo,db,storage,LiteDb,var,public
From: https://www.cnblogs.com/lanwah/p/18242599

相关文章

  • c# LiteDB的基础用法
    LiteDB是一个轻量级的嵌入式NoSQL数据库,其设计理念与MongoDB类似,但它是完全使用C#开发的,因此与C#应用程序的集成非常顺畅。与SQLite相比,LiteDB提供了NoSQL(即键值对)的数据存储方式,并且是一个开源且免费的项目。它适用于桌面、移动以及Web应用程序。安装LiteDB包......
  • C# LiteDB 初使用
    LiteDB是一个轻量级的.NET数据库,它完全用C#编写,不需要安装任何外部依赖或服务器。它非常适合用于嵌入式数据库、桌面应用程序或小型Web项目。以下是如何在C#中使用LiteDB的基本步骤:安装  LiteDB通过NuGet安装LiteDB。在VisualStudio中,右键点击你的项目->......
  • LiteDB
    LiteDB.dll今天也是第一次见,并且系统里确实这个dll,在网上查了下,并记录下原文链接:https://www.modb.pro/wiki/1610LiteDB是一个.NET开发的小型快速轻量级的NoSQL嵌入式数据库。产品特性无服务器NoSQL文档存储简单的API,类似于MongoDB单个DLL(小于450kb)中的.NET4.5/NE......
  • Blazor的呈现模式与LiteDB项目中的坑点
    参照文档指引,准备用.NET8的Blazor和LiteDB撸个小项目,结果引入的LiteDB相关代码一直无法访问目录中的数据库,重建了好几次项目都无果。琢磨了半天才发现自己踩了新版本Blazor的呈现模式(RenderMode)的坑。看来还是要持续学习.NET新技术,跟上时代步伐!解决方案先给出我琢磨出来的解决......
  • LiteDB数据库
    LiteDB属于是嵌入式的文档型数据库。有点像关系型数据库里的SQLite。数据库的使用起来跟MongoDB比较像。区别是,LiteDB不需要部署服务端,像SQLite一样,直接保存在.db文件中。安装Install-PackageLiteDB使用示例://创建你的POCO类usingLiteDB;usingNewtonsoft.Json;//......
  • LiteDB 异常问题汇集
    1、LiteDBENSURE:getonlyindexbelowhighestindex===================================================在LiteDB.Constants.ENSURE(Booleanconditional,Stringmessage)位置C:\Users\DELL\Desktop\litedb损坏\LiteDB.Studio-master\LiteDB.Studio\ICSharpCod......
  • 通用的CRUD之LiteDB
    前言你要开发一个系统,是不是首要任务是先建库,建表,建字段,既所谓的数据建模(听起来高大上一点,数据建模也确实是个烧脑的活),要费不少功夫。不知你是否遇到过这样的场景。A产品有3个测试参数,B产品有6个测试参数,而且值和类型都各不相同,用SQL你要怎么建表呢?有人会说这简单“参数名,参数......
  • WinUI(WindowsAppSDK)使用LiteDB做个女演员图鉴
    为什么选择LiteDB之前做uwp的时候有做过一个植物图鉴,当时图片使用的是在线图片,所以图片很多也并没有什么体验上的差别,但是直到有一天别人的网站挂掉了,图片访问不到了,当时......