提交代码
This commit is contained in:
@@ -0,0 +1,88 @@
|
||||
using LiteDB;
|
||||
|
||||
namespace HardwareControl.Core.SystemSetting
|
||||
{
|
||||
/// <summary>
|
||||
/// 系统参数配置的本地存储层(LiteDB)。
|
||||
/// 数据库文件由调用方指定,建议整个进程只注册一个实例。
|
||||
/// </summary>
|
||||
public sealed class SystemConfigRepository : IDisposable
|
||||
{
|
||||
private const string CollectionName = "system_config";
|
||||
|
||||
private readonly LiteDatabase _database;
|
||||
private readonly ILiteCollection<SystemConfig> _collection;
|
||||
|
||||
public SystemConfigRepository(string databasePath)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(databasePath))
|
||||
{
|
||||
throw new ArgumentException("数据库路径不能为空", nameof(databasePath));
|
||||
}
|
||||
|
||||
var fullPath = Path.GetFullPath(databasePath);
|
||||
var directory = Path.GetDirectoryName(fullPath);
|
||||
if (!string.IsNullOrWhiteSpace(directory))
|
||||
{
|
||||
Directory.CreateDirectory(directory);
|
||||
}
|
||||
|
||||
_database = new LiteDatabase(new ConnectionString
|
||||
{
|
||||
Filename = fullPath,
|
||||
Connection = ConnectionType.Shared,
|
||||
});
|
||||
_collection = _database.GetCollection<SystemConfig>(CollectionName);
|
||||
}
|
||||
|
||||
/// <summary>读取全部配置,可按关键字过滤(分类、名称、值、描述)。</summary>
|
||||
public IReadOnlyList<SystemConfig> GetAll(string? keyword = null)
|
||||
{
|
||||
var items = _collection
|
||||
.FindAll()
|
||||
.OrderBy(x => x.ConfigClass)
|
||||
.ThenBy(x => x.ConfigName)
|
||||
.ToList();
|
||||
|
||||
if (string.IsNullOrWhiteSpace(keyword))
|
||||
{
|
||||
return items;
|
||||
}
|
||||
|
||||
var value = keyword.Trim();
|
||||
return items
|
||||
.Where(x =>
|
||||
Contains(x.ConfigClass, value) ||
|
||||
Contains(x.ConfigName, value) ||
|
||||
Contains(x.ConfigValue, value) ||
|
||||
Contains(x.ConfigDescript, value))
|
||||
.ToList();
|
||||
}
|
||||
|
||||
public SystemConfig? FindById(int id) => _collection.FindById(id);
|
||||
|
||||
public SystemConfig Insert(SystemConfig config)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(config);
|
||||
|
||||
config.ConfigId = 0;
|
||||
var id = _collection.Insert(config);
|
||||
config.ConfigId = id.AsInt32;
|
||||
return config;
|
||||
}
|
||||
|
||||
public bool Update(SystemConfig config)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(config);
|
||||
return _collection.Update(config);
|
||||
}
|
||||
|
||||
public bool Delete(int id) => _collection.Delete(id);
|
||||
|
||||
public void Dispose() => _database.Dispose();
|
||||
|
||||
private static bool Contains(string? source, string value) =>
|
||||
source is not null &&
|
||||
source.Contains(value, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user