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 write a LINQ to Entities query that can filter by using the strongly-typed property SampleId. For example:
db.Cases.Where(x=>targetlist.Contains(x.SampleId))
where targetlist is a list of items from the filter.
So, in effect, is there a way to write a query such that "SampleId" can directly translate to Case.SampleId?
I have tried reflection and made use of the GetProperty and GetValue and LINQ to Entities does not like it.
Any suggestions will be much appreciated!
EDIT (by pid for original poster srinaik2020):
@zaitsman: this is the code posted in an comment further below and is the actual resolution of the problem, based on the accepted answer.
public static class MyExtensions
{
public static string GetPropertyByName(this CaseV case1, string name)
{
var x = typeof (CaseV).GetProperty(name).GetValue(case1);
if (x != null)
{
return x.ToString();
} else {
return "none";
}
}
}
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:
Once this is working, you'll want just to set and/or get the value of the property. The
GetProperty()
method above just returns thePropertyInfo
object. To get or set the value you'll have to use the appropriate methods ofPropertyInfo
.I'd not expose the
PropertyInfo
because it would ruin the magic.Better have to extension methods, then:
if you like expressions, you can use them to get the value of a property like so (taken from some helpers i have made in LinqPad so it might not be full code):
and then do