How do you check if a property has IsRequired() on an object using reflection?

Viewed 44

I have a string property it is configured as IsRequired() using FluentAPI. How do I check if this property is required? I'm iterating through all properties of my object using reflection.

1 Answers

It is not possible to achieve this via reflection cause Fluent API does not emit any CLR type data (if you have used data annotations it would be quite trivial just by looking for corresponding attributes on properties). You will need to examine the Model property of the context or EntityType of the DbSet to get this metadata. Something along this lines, for example:

// var entityType = ctx.Model.GetEntityTypes()
//    .Where(type => type.ClrType == typeof(Person))
//    .First();
// or
var entityType = ctx.Persons.EntityType;
var property = entityType.FindProperty("PrimaryAddressId");
var required = !property.IsNullable;
Related