LINQ to Entities-使用字符串名称寻址类属性 [英] LINQ to Entities - Addressing class properties with their string names
问题描述
我有一个Kendo网格,其中启用了服务器端筛选.要过滤的字段以字符串形式传递.例如,我要按"SampleId"进行过滤.现在,我需要编写一个LINQ to Entities查询,该查询可以使用强类型属性SampleId进行过滤.例如:
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))
其中targetlist是过滤器中的项目列表.
where targetlist is a list of items from the filter.
实际上,有没有一种方法可以编写查询,使"SampleId"可以直接转换为Case.SampleId?
So, in effect, is there a way to write a query such that "SampleId" can directly translate to Case.SampleId?
我尝试了反射,并使用了GetProperty和GetValue,而LINQ to Entities不喜欢它.
I have tried reflection and made use of the GetProperty and GetValue and LINQ to Entities does not like it.
任何建议将不胜感激!
编辑(由pid制作,原始海报srinaik2020):
EDIT (by pid for original poster srinaik2020):
@zaitsman:这是在下面的评论中发布的代码,并且是根据接受的答案实际解决问题的方法.
@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.
以下是指针:
- Extension methods
- GetProperty()
一旦工作,您将只想设置和/或获取属性的值.
上面的GetProperty()
方法仅返回PropertyInfo
对象.
要获取或设置值,您必须使用PropertyInfo
的适当方法.
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
.
我不会公开PropertyInfo
,因为它会破坏神奇.
I'd not expose the PropertyInfo
because it would ruin the magic.
最好使用扩展方法,然后:
Better have to extension methods, then:
T GetPropertyByName<T>(string name);
SetPropertyByName<T>(string name, T value);
这篇关于LINQ to Entities-使用字符串名称寻址类属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!