Gerald Gonzales
Gerald Gonzales

Reputation: 533

Entity Framework get properties including some values

I have a method which iterates through all the properties of an object. I am logging those properties:

Object obj = entry.Entity;
Type type = obj.GetType();
PropertyInfo[] properties = type.GetProperties();

 foreach (PropertyInfo property in properties)
 {
     oldData.AppendFormat("{0}={1} || ", property.Name, property.GetValue(obj, null));
 }

Now this is working fine but on my table log, it is also writing this properties below:

- PremiumReference=System.Data.Objects.DataClasses.EntityReference`1[Data.Premium]
- EntityState=Deleted
- EntityKey=System.Data.EntityKey

Any ideas how I can filter this properties?

Upvotes: 3

Views: 3363

Answers (3)

Dom84
Dom84

Reputation: 864

Have a look in here

BindingFlags-Enumeration

Maybe it helps using the flag DeclaredOnly in combination with the other flags you need in your scenario to match your needs.

Upvotes: 2

Gerald Gonzales
Gerald Gonzales

Reputation: 533

I solved my issue with this code below:

PropertyInfo[] properties = obj.GetType().GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance)
            .Where(pi => !(pi.PropertyType.IsSubclassOf(typeof(EntityObject))) && !(pi.PropertyType.IsSubclassOf(typeof(EntityReference))))
            .ToArray();

The BindingFlags did help but I do not also want the EntityReference and EntityObject so I needed to add the where clause.

How to get all names of properties in an Entity?

Upvotes: 1

Lukas Abfalterer
Lukas Abfalterer

Reputation: 104

Every Entity in Entity Framework has a property with the enumeration EntityState. EF adds them to the object.

If you add an Object to EF it marks it as EntityState.Added.

Hope it helps.

See Entity Framework EntityState

Upvotes: 2

Related Questions