问题描述
我正在尝试通过Entity Framework Core的.HasMaxLength属性进行验证.
I'm trying to validate against the .HasMaxLength property from Entity Framework Core.
这是示例模型构建器方法:
Here is a sample model builder method:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Address>(entity =>
{
entity.Property(e => e.AddressEmail)
.IsRequired()
.HasMaxLength(255)
.IsUnicode(false)
.HasDefaultValueSql("('')");
使用我的上下文,我可以找到最大长度,如下所示:
Using my context, I can find the maximum length like this:
dbContext.Model.FindEntityType(typeof(Address)).FindProperty("AddressEmail").GetMaxLength()
使用Fluent验证,我可以这样做:
Using Fluent Validation, I can do this:
RuleFor(Address => Address.AddressEmail).NotNull().MaximumLength(255);
这可行,但是,当我更改数据库结构时,我必须更新验证器.
So that works but, when I change the database structure, I have to update my validators.
我试图找出如何从实体框架MaxLength属性驱动我的Fluent Validation规则
I'm trying to figure out how to drive my Fluent Validation rules from the entity framework MaxLength property
任何帮助将不胜感激.
****引入dbcontext的部分工作方式,但我仍在努力获取规则:
**** Partially working way of bringing the dbcontext in but I still am struggling getting the rule:
public AddressValidator(DbContext dbContext)
{
Microsoft.EntityFrameworkCore.Metadata.IEntityType et = dbContext.Model.FindEntityType(typeof(Address));
foreach (var Property in et.GetProperties())
{
var maxLength = Property.GetMaxLength();
---->>>>> RuleFor(x =>x.{PropertyName}) Invalid but this is the idea
}
推荐答案
您可以使用之前提供的代码将db上下文注入到验证器中.不确定是否有适配器可以自动执行
You can inject your db context into validator using the code you provided before. Not sure if there is an adapter that does it automatically
class MyClassValidator : AbstractValidator<MyClass>
{
public MyClassValidator(MyDbContext dbContext)
{
var maxLength = dbContext.Model.FindEntityType(typeof(MyClass))
.FindProperty(nameof(MyClass.Data)).GetMaxLength();
RuleFor(x => x.Data)
.MaximumLength(maxLength.Value);
}
}
更新
使用表达式的版本
class MyClassValidator : AbstractValidator<MyClass>
{
public MyClassValidator(MyDbContext dbContext)
{
var entityType = dbContext.Model.FindEntityType(typeof(MyClass));
foreach (var property in typeof(MyClass).GetProperties()
.Where(x => x.PropertyType == typeof(string)))
{
var maxLength = entityType
.FindProperty(property.Name)
.GetMaxLength();
if (maxLength.HasValue)
{
var parameter = Expression.Parameter(typeof(MyClass));
var memberExpression = Expression.Property(parameter, property.Name);
var lambdaExpression = Expression.Lambda<Func<MyClass, string>>(memberExpression, parameter);
RuleFor(lambdaExpression)
.MaximumLength(maxLength.Value);
}
}
}
}
这篇关于如何使用Fluent验证针对实体框架核心字段属性进行验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!