You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

50 lines
1.7 KiB

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;
}
}
}