我们目前正在尝试将实体框架元数据获取到我们的视图模型中,并且我们已经查询了模型构建器,我们能够获得最大长度,但是,我们无法获得"isRequired“IProperty。
// What our controller looks like:
var maxLengthOfStrings = _db.Model
.FindEntityType(typeof(Validation))
.GetProperties()
.Where(p => p.ClrType == typeof(string))
.ToDictionary(prop => prop.Name, prop => new {
MaxLegnth = prop.GetMaxLength(),
// The part that is saying required doesn't exist
// in the context
IsRequired = prop.IsRequired()
});
// What our db context file looks like:
modelBuilder.Entity<DeploymentEnvironment>(entity =>
{
entity.HasKey(e => e.Code);
entity.Property(e => e.Code)
.HasMaxLength(100)
.ValueGeneratedNever();
entity.Property(e => e.Name)
.IsRequired()
.HasMaxLength(200);
});
收到的错误是"IProperty不包含"IsRequired“的定义,并且找不到接受"IProperty”类型的第一个参数的可访问扩展方法"IsRequired“。
发布于 2019-06-21 03:19:35
我认为您需要将PropertyInfo转换为PropertyDescriptor,然后检查属性。如下所示:
IsRequired = p.Cast<PropertyDescriptor>().Where(p => p.Attributes.Cast<Attribute>().Any(a => a.GetType() == typeof(RequiredAttribute)))
https://stackoverflow.com/questions/56692105
复制相似问题