1

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.

User123
  • 549
  • 1
  • 11
  • 24

1 Answers1

2

It is not possible to achieve this via reflection because 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;
halfer
  • 19,824
  • 17
  • 99
  • 186
Guru Stron
  • 102,774
  • 10
  • 95
  • 132
  • On my dbcontext, there is no Model property nor a EntityType on the dbset. – User123 Sep 21 '22 at 13:13
  • @User123 what version of EF are you using? – Guru Stron Sep 21 '22 at 15:25
  • Entity Framework 6 – User123 Sep 21 '22 at 15:35
  • I used an extension method (https://stackoverflow.com/a/51965836/5731463) that returns EntityType, and when I did the check like this _context.GetEntityMetadata().Properties["Code"].Nullable, it returned true. I was expecting False. My property is registered as IsRequired using FluentApi – User123 Sep 21 '22 at 15:39
  • I checked another property that is also not null in the db (int, not null) and it returns false for nullable. Wondering if Nullable is returning true because the CLR type is string in which case this doesnt help at all. – User123 Sep 21 '22 at 15:48
  • @User123 I don't have EF 6 setup available, can't say, sorry. – Guru Stron Sep 21 '22 at 15:55