自定义MVC数据验证属性,如何通过反射动态创建表达式树

我现在在路上 我现在在路上 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区

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


把表达式树改成动态创建,根据特性使用的类和属性。表达式树没研究过...一下就搞反射表达式树,被搞的一头雾水,求指点
...全文

相关推荐

评论 7
收藏 已收藏
分享
返回顶部
我现在在路上
.NET社区 62,271 成员 668,968 内容