0

In our Entity Framework schema, we have a view that contains multiple fields both nullable and non-nullable. Because it is a view, Entity Framework assigns a entity key on all non-nullable field. This causes our query to return fewer rows than what the database is returning. If we correctly set the entity keys, we have the right number of rows.

We would like to put a safe check that, when the application start, will check if the entity keys are set on the right fields. We want to do that in case someone has to delete and add the view again to the EDMX.

How can I get the entity keys of a DbSet so I can verify if the keys are properly set?

Community
  • 1
  • 1
Pierre-Alain Vigeant
  • 21,135
  • 7
  • 60
  • 101

1 Answers1

0

You'll have to use reflection to get the fields where KeyAttribute is used:

 var t = typeof(YourClass);
 var properties = t.GetProperties();
 var keyProps = new List<string>();

foreach (var prop in properties) 
{
     if (Attribute.IsDefined(prop , typeof(Key)))
     {
         keyProps.Add(prop.Name);
     }
}
DrewJordan
  • 5,032
  • 1
  • 21
  • 39