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
|
{
|
/// <summary>
|
/// 将字典列表转换为指定类型的对象列表
|
/// </summary>
|
/// <typeparam name="T">目标对象类型</typeparam>
|
/// <param name="dicList">源字典列表</param>
|
/// <returns>转换后的对象列表</returns>
|
public static List<T> DicToIEnumerable<T>(this List<Dictionary<string, object>> dicList)
|
{
|
List<T> list = new List<T>();
|
foreach (Dictionary<string, object> dic in dicList)
|
{
|
list.Add(dic.DicToModel<T>());
|
}
|
return list;
|
}
|
|
/// <summary>
|
/// 将字典转换为指定类型的模型对象
|
/// </summary>
|
/// <typeparam name="T">目标模型类型</typeparam>
|
/// <param name="dic">包含属性值的字典</param>
|
/// <returns>转换后的模型对象</returns>
|
/// <remarks>
|
/// 1. 支持通过属性名、首字母大写或小写的属性名从字典中查找值
|
/// 2. 处理了SugarColumn特性的特殊逻辑:主键/自增字段跳过,非空字段校验
|
/// 3. 自动进行类型转换
|
/// </remarks>
|
/// <exception cref="Exception">当非空字段值为null或空时抛出异常</exception>
|
public static T DicToModel<T>(this Dictionary<string, object> dic)
|
{
|
T model = Activator.CreateInstance<T>();
|
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<SugarColumn>();
|
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;
|
}
|
}
|
}
|