5 changed files with 143 additions and 65 deletions
@ -0,0 +1,49 @@ |
|||||
|
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<string> ValidateDataLength<T>(IList<T> dataList, DbContext dbContext) where T : class |
||||
|
{ |
||||
|
var errors = new List<string>(); |
||||
|
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<ImporterHeaderAttribute>()?.Name; |
||||
|
return ret; |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
} |
Loading…
Reference in new issue