LMS.service/LMS.DAO/OptionDAO/OptionGlobalDAO.cs

68 lines
2.2 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using LMS.Repository.DB;
using Microsoft.EntityFrameworkCore;
namespace LMS.DAO.OptionDAO
{
public class OptionGlobalDAO(ApplicationDbContext dbContext)
{
private readonly ApplicationDbContext _dbContext = dbContext;
/// <summary>
/// 根据配置键查找并返回指定类型的配置值
/// </summary>
/// <typeparam name="T">返回值类型</typeparam>
/// <param name="optionKey">配置键</param>
/// <returns>配置值,如果不存在或转换失败则返回默认值</returns>
public async Task<T?> FindAndReturnOption<T>(string optionKey)
{
// 参数验证
if (string.IsNullOrWhiteSpace(optionKey))
{
return default(T);
}
var options = await _dbContext.Options
.Where(x => x.Key == optionKey)
.FirstOrDefaultAsync();
if (options == null) return default;
// 直接返回转换结果GetValueObject内部应该处理null情况
return options.GetValueObject<T>() ?? default;
}
/// <summary>
/// 检查配置是否存在
/// </summary>
/// <param name="optionKey">配置键</param>
/// <returns>是否存在</returns>
public async Task<bool> OptionExists(string optionKey)
{
if (string.IsNullOrWhiteSpace(optionKey))
{
return false;
}
return await _dbContext.Options
.AnyAsync(x => x.Key == optionKey);
}
/// <summary>
/// 获取多个配置
/// </summary>
/// <param name="optionKeys">配置键列表</param>
/// <returns>配置字典</returns>
public async Task<Dictionary<string, Options>> GetMultipleOptions(params string[] optionKeys)
{
if (optionKeys == null || optionKeys.Length == 0)
{
return new Dictionary<string, Options>();
}
var options = await _dbContext.Options
.Where(x => optionKeys.Contains(x.Key))
.ToListAsync();
return options.ToDictionary(x => x.Key, x => x);
}
}
}