简体   繁体   中英

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?

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

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.

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM