首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Entity Framework类中是否有"isRequired“属性?正在尝试获取模型的元数据属性

Entity Framework类中是否有"isRequired“属性?正在尝试获取模型的元数据属性
EN

Stack Overflow用户
提问于 2019-06-21 02:41:55
回答 1查看 106关注 0票数 1

我们目前正在尝试将实体框架元数据获取到我们的视图模型中,并且我们已经查询了模型构建器,我们能够获得最大长度,但是,我们无法获得"isRequired“IProperty。

代码语言:javascript
复制
// 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“。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-06-21 03:19:35

我认为您需要将PropertyInfo转换为PropertyDescriptor,然后检查属性。如下所示:

代码语言:javascript
复制
IsRequired = p.Cast<PropertyDescriptor>().Where(p => p.Attributes.Cast<Attribute>().Any(a => a.GetType() == typeof(RequiredAttribute)))
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56692105

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档