alex
alex

Reputation: 720

Loop through all the properties of an entity object and get the corresponding value?

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.

Upvotes: 2

Views: 3745

Answers (1)

MakePeaceGreatAgain
MakePeaceGreatAgain

Reputation: 37000

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.

Upvotes: 3

Related Questions