Cricket
Cricket

Reputation: 185

Is there an "isRequired" property in Entity Framework class? Trying to get metadata properties to the model

We are currently trying to get entity framework metadata to our viewmodel and we have queried the model builder and we're able to get the maximum length, however, we cannot get the "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);
         });

The error being received is "IProperty does not contain a definition for "IsRequired" and no accessible extension method "IsRequired" accepting a first argument of the type "IProperty" could be found.

Upvotes: 2

Views: 387

Answers (1)

Eduardo Silva
Eduardo Silva

Reputation: 625

I believe you need to Cast PropertyInfo to PropertyDescriptor and then, check the Attributes. Something like this:

IsRequired = p.Cast<PropertyDescriptor>().Where(p => p.Attributes.Cast<Attribute>().Any(a => a.GetType() == typeof(RequiredAttribute)))

Upvotes: 2

Related Questions