using Magicodes.ExporterAndImporter.Core; using Microsoft.AspNetCore.Http; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.IdentityModel.Tokens; using System.Globalization; using System.Reflection; using Wood.Util.ExtensionMethods; using static Dapper.SqlMapper; namespace Wood.Service { public static class ValidationHelper { public static List ValidateDataLength(IList dataList, DbContext dbContext) where T : class { var errors = new List(); var entityType = dbContext.Model.FindEntityType(typeof(T)); int rowNum = 2; foreach (var data in dataList) { foreach (var property in entityType.GetProperties()) { var maxLength = property.GetMaxLength(); if (maxLength > 0 && property.ClrType == typeof(string)) { var value = property.PropertyInfo.GetValue(data) as string; if (!string.IsNullOrEmpty(value) && value.Length > maxLength) { string title = property.GetImporterHeader_Name(); errors.Add($"第{rowNum}行数据错误:字段 {(title.IsNullOrEmpty() ? property.Name : title)} 的长度超过限制 ({value.Length} > {maxLength})"); } } string format = property.GetImporterHeader_Format(); if (format.HasValue()) { if (format == "yyyy-MM-dd" || format == "yyyy-MM-dd HH:mm:ss") { var value = property.PropertyInfo.GetValue(data) as string; if (DateTime.TryParse(value, out DateTime result) == false) { string title = property.GetImporterHeader_Name(); errors.Add($"第{rowNum}行数据错误:字段 {(title.IsNullOrEmpty() ? property.Name : title)} 的格式错误 (格式:{format},字段值:{value})"); } } } } rowNum++; } return errors; } } public static class PropertyExtension { public static string GetImporterHeader_Name(this IProperty value) { string ret = value?.PropertyInfo?.GetCustomAttribute()?.Name; return ret; } public static string GetImporterHeader_Format(this IProperty value) { string ret = value?.PropertyInfo?.GetCustomAttribute()?.Format; return ret; } } public static class SearchControlExtension { /// /// 忽略双字节的PadRight功能,汉字的length = 2 /// /// /// /// /// public static string PadRightByte(this string str, int totalWidth, char paddingChar = ' ') { if (str == null) { str = ""; } int strLen = System.Text.UTF8Encoding.Default.GetBytes(str).Length; int actualWidth = (totalWidth > strLen) ? (totalWidth - strLen) : 0; return str + "".PadLeft(actualWidth, paddingChar); } } }