2

I'm using Entity framework 6 DBContext , Database First.

Let's say that I have an object , myobj1 from one of entity.

Is there any way to loop through all the properties of this object and to get current value of each of them ?

Of course I need a general code that should work for any object from any entity.

Codor
  • 17,447
  • 9
  • 29
  • 56
alex
  • 694
  • 3
  • 15
  • 35
  • 2
    i think reflection can help you – Disappointed Jul 30 '15 at 10:56
  • possible duplicate of [How do you get the all properties of a class and its base classes (up the hierarchy) with Reflection? (C#)](http://stackoverflow.com/questions/245055/how-do-you-get-the-all-properties-of-a-class-and-its-base-classes-up-the-hierar) – Fabjan Jul 30 '15 at 11:03

1 Answers1

3

Something like this:

var values = instance.GetType().GetProperties().Select(x => x.GetValue(instance, null));

If you also want the name of the property use this:

var values = instance.GetType().GetProperties().Select(x => 
        new 
        {
            property = x.Name, 
            value = x.GetValue(instance, null)
        })
        .ToDictionary(x => x.property, y => y.value);

This selects all the properties of the given type and gets its name and value for the desired instance.

However this approach only works for simple, non-indexed properties.

EDIT: Also have a look on MSDN on Bindingflags to restrict the properties returned from GetType().GetProperties - in particular when you need the properties of your base-class also.

MakePeaceGreatAgain
  • 35,491
  • 6
  • 60
  • 111