using Magicodes.ExporterAndImporter.Core; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.IdentityModel.Tokens; using System.Reflection; 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 = 1; 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(); errors.Add($"第{rowNum}行数据错误:字段 {(title.IsNullOrEmpty() ? property.Name : title)} 的长度超过限制 ({value.Length} > {maxLength})"); } } } rowNum++; } return errors; } } public static class PropertyExtension { public static string GetImporterHeader(this IProperty value) { string ret = value?.PropertyInfo?.GetCustomAttribute()?.Name; return ret; } } }