LINQ to Entities - Addressing class properties with their string names

前端 未结 3 1214
小蘑菇
小蘑菇 2021-01-16 20:12

I have a Kendo grid that has serverside filtering turned on. The field to filter by is passed as a string. For example, I want to filter by \"SampleId\". Now, I need to writ

3条回答
  •  星月不相逢
    2021-01-16 21:05

    You can use an extension method and attach it to the class.

    That method should use reflection to retrieve the property from the object.

    Here are the pointers:

    • Extension methods
    • GetProperty()

    Once this is working, you'll want just to set and/or get the value of the property. The GetProperty() method above just returns the PropertyInfo object. To get or set the value you'll have to use the appropriate methods of PropertyInfo.

    I'd not expose the PropertyInfo because it would ruin the magic.

    Better have to extension methods, then:

    T GetPropertyByName(string name);
    SetPropertyByName(string name, T value);
    

提交回复
热议问题