using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace WIDESEA_Core.Helper
{
public static class ObjectExtension
{
///
/// 将字典列表转换为指定类型的对象列表
///
/// 目标对象类型
/// 源字典列表
/// 转换后的对象列表
public static List DicToIEnumerable(this List> dicList)
{
List list = new List();
foreach (Dictionary dic in dicList)
{
list.Add(dic.DicToModel());
}
return list;
}
///
/// 将字典转换为指定类型的模型对象
///
/// 目标模型类型
/// 包含属性值的字典
/// 转换后的模型对象
///
/// 1. 支持通过属性名、首字母大写或小写的属性名从字典中查找值
/// 2. 处理了SugarColumn特性的特殊逻辑:主键/自增字段跳过,非空字段校验
/// 3. 自动进行类型转换
///
/// 当非空字段值为null或空时抛出异常
public static T DicToModel(this Dictionary dic)
{
T model = Activator.CreateInstance();
PropertyInfo[] propertyInfos = typeof(T).GetProperties(BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance);
foreach (var property in propertyInfos)
{
object? value = null;
if (!dic.TryGetValue(property.Name, out value))
{
if (!dic.TryGetValue(property.Name.FirstLetterToUpper(), out value))
{
if (!dic.TryGetValue(property.Name.FirstLetterToLower(), out value))
{
continue;
}
}
}
SugarColumn? sugarColumn = property.GetCustomAttribute();
if (sugarColumn != null)
{
if ((value == null || value.Equals("")))
{
if (sugarColumn.IsIdentity || sugarColumn.IsPrimaryKey)
continue;
else if (sugarColumn.IsNullable)
{
property.SetValue(model, value);
}
else
{
throw new Exception($"The value of {property.Name} is null or empty, but it is not allowed to be null or empty.");
}
}
else
{
property.SetValue(model, value.ChangeType(property.PropertyType));
}
if (sugarColumn.IsIdentity || sugarColumn.IsPrimaryKey)
continue;
}
if (value != null && sugarColumn != null && !sugarColumn.IsNullable)
property.SetValue(model, value.ChangeType(property.PropertyType));
}
return model;
}
}
}