I'm using WCF RIA services to do a few small pieces of a web application; mainly populate/filter lists (I don't understand RIA well enough yet to trust I'm doing server side validation correct). One of the things I do is get a list of which fields have which generic type, by which I mean, strings are a text type, decimal, double, integer are numeric, etc. I do that with a LINQ query
Fields = type.GetProperties().Where(pi => pi.PropertyType == typeof(string) && pi.GetGetMethod() != null && pi.Name != "DisplayName")
.Select(pi => new FieldData
{
FieldName = CommonResources.AddSpacesToSentence(pi.Name, true),
FieldType = "Text"
}).....
The field DisplayName
is a special field that should be ignored in lists, but as this application is growing I realize this isn't a very maintainable/expandable/buzzwordable way to go about this. What I really want is to know is if metadata for the DisplayName
property has the attribute [Display(AutoGenerateField = false)]
Is there a way I can check for that in my LINQ?
Update:
After posting this I was able to slowly work out how to do this (I've never worked with Attributes in this way before). The answer given by King King looks nice and is very generic, but the way I wound up solving this was different, so if you're interested in another way, here's what I found. I added this to the LINQ query:
((DisplayAttribute)Attribute.GetCustomAttribute(pi, typeof(DisplayAttribute))).GetAutoGenerateField() == false
You can use the GetCustomAttributes
method to filter properties with the given attribute:
...
.Where(pi => pi.GetCustomAttributes(typeof(DisplayAttribute), true).Any())
...
The true
argument includes inheritance in attribute search.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With