Reputation: 185
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
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