62,046
社区成员
发帖
与我相关
我的任务
分享
public class OnlyOneAttribute : ValidationAttribute
{
public OnlyOneAttribute()
{
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
using (var context = new EfDbContext())
{
//验证属性父对象的类型
var type = validationContext.ObjectType;
//获取该类型的仓储类型
var typeRepository = typeof (EfRepository<>);
var genericType = typeRepository.MakeGenericType(type);
//获取该类型的仓储对象 EfRepository<Student>
var o = Activator.CreateInstance(genericType, context);
//FirstOrDefault参数的表达树 需要修改的地方
var expressionType = typeof (Expression<Func<Student, bool>>);
//获取对应参数的FirstOrDefault方法
var method = genericType.GetMethod("FirstOrDefault",new Type[] { expressionType });
//表达式 需要修改的地方
Expression<Func<Student, bool>> func = (s) => s.UserName == value.ToString();
var result = method.Invoke(o, new object[] {func});
if (result != null)
{
var errorMessage = FormatErrorMessage(validationContext.DisplayName);
return new ValidationResult(errorMessage);
}
}
return ValidationResult.Success;
}
}
private readonly string _property;
public OnlyOneAttribute(string property)
{
_property = property;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (value==null)
return new ValidationResult("值不能为null");
using (var context = new EfDbContext())
{
//验证属性父对象的类型
var type = validationContext.ObjectType;
//获取该类型的仓储类型
var typeRepository = typeof (EfRepository<>);
var genericType = typeRepository.MakeGenericType(type);
//获取该类型的仓储对象 EfRepository<Student>
var o = Activator.CreateInstance(genericType, context);
//FirstOrDefault参数的表达树
var expressionType = typeof (Expression<>).MakeGenericType(typeof(Func<,>).MakeGenericType(new Type[] {type,typeof(bool)}));
//获取对应参数的FirstOrDefault方法
var method = genericType.GetMethod("FirstOrDefault",new Type[] { expressionType });
//动态表达式树
var param = Expression.Parameter(type, "x");
var expr = Expression.Lambda(typeof(Func<,>).MakeGenericType(type, typeof(bool)),
Expression.Equal(
Expression.Property(param, _property),
Expression.Constant(value.ToString())
), param);
var result = method.Invoke(o, new object[] { expr });
if (result != null)
{
var errorMessage = FormatErrorMessage(validationContext.DisplayName);
return new ValidationResult(errorMessage);
}
}
return ValidationResult.Success;
}
结贴给分
var param = Expression.Parameter(type, "x");
var expr = Expression.Lambda(typeof(Func<,>).MakeGenericType(type, typeof(bool)),
Expression.Equal(
Expression.Property(param, "UserName"),
Expression.Constant(value.ToString())
), param);