當獲取一個類型(class)的所有屬性時,想排除指定屬性,該如何操作?
比如:EF中一個實體類型UserEntity,通過反射獲取這個類的屬性時,想排除這個為映射的字段ID
使用以下方法即可!
PropertyInfo[] props =entity.GetType().GetProperties().Where(v => v.GetCustomAttributes(typeof(NotMappedAttribute), true).Length == 0).ToArray();//排除未映射的字段
//更優雅的方法 PropertyInfo[] props = entity.GetType().GetProperties().Where(pi => !Attribute.IsDefined(pi, typeof(NotMappedAttribute))).ToArray();//排除未映射字段
參考:http://stackoverflow.com/questions/2051834/exclude-property-from-gettype-getproperties