在使用Reflection的LINQ查询中使用字符串值 [英] Using string value in a LINQ query using Reflection
问题描述
您好,
我正在尝试使用字符串值替换表示数据库中字段名称的lambda表达式。原因是,我正在创建一个Print()方法,它将读取传入的值,然后从它们构造一个LINQ查询。我想拿这个
......
public ActionResult 打印( string varOne)
        {
; 列表< MainView > model = db.MainViews.OrderByDescending(x
=> x.CaseName)
&NBSP; &NBSP; &NBSP; &NBSP; &NBSP; return 查看(模型);
&NBSP;&NBSP;&NBSP; }
...并将其转换为此...
&NBSP; &NBSP; public ActionResult Print(string varOne)
&NBSP; &NBSP; &NBSP; {
&NBSP; &NBSP; &NBSP; &NBSP; &NBSP;列表与LT;&的MainView GT; model = db.MainViews.OrderByDescending(x => x.GetType()。GetProperty(varOne).GetValue(x,null))
&NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP; .ToList();&NBSP; &NBSP; &NBSP; &NBSP; &NBSP; &NBSP;
&NBSP; &NBSP; &NBSP; &NBSP; &NBSP;返回查看(型号);
&NBSP; &NBSP; &NBSP; }
哪个应该有效,但我收到错误...
{" LINQ to Entities无法识别方法'System.Object GetValue(System.Object,System.Object [])'方法,此方法无法转换为商店表达式。"}
不知道从哪里开始,任何答案都会有所帮助。
谢谢!
嗨tumoheat364,
我们可以使用Dynamic LINQ实现它,请安装动态LINQ Via Nuget。右键单击您的项目 - >管理Nuget包.. - >在搜索字段中键入关键字 System.linq.dynamic - >选择 System.linq.dynamic并点击安装。
然后你可以像这样编写相关的lambda表达式:
请在安装软件包后使用System.Linq.Dynamic使用。
public ActionResult Print(string varOne)
{
List< MainView> model = db.MainViews.OrderBy(
" {varOne} desc")。ToList();
return View(model);
}
祝你好运,
章龙
Hello,
I am trying to replace a lambda expression that represents a field name in my database with a string value. The reason is, I am creating a Print() method that will read the incoming values, then construct a LINQ query from them. I want to take this...
public ActionResult Print(string varOne)
{
List<MainView> model = db.MainViews.OrderByDescending(x => x.CaseName)
return View(model);
}
...and convert it to this...
public ActionResult Print(string varOne)
{
List<MainView> model = db.MainViews.OrderByDescending(x => x.GetType().GetProperty(varOne).GetValue(x, null))
.ToList();
return View(model);
}
which should work, but I get the error ...
{"LINQ to Entities does not recognize the method 'System.Object GetValue(System.Object, System.Object[])' method, and this method cannot be translated into a store expression."}
Not sure where to go from here, any answers would help.
Thank you!
Hi tumoheat364,
We could achieve it by using Dynamic LINQ, Please install Dynamic LINQ Via Nuget. Right click your project -> Manage Nuget Package.. -> type the keyword System.linq.dynamic in search field -> select System.linq.dynamic and click install. Then you could write related lambda Expression like this:
Please using using System.Linq.Dynamic after installed the packages.
public ActionResult Print(string varOne) { List<MainView> model = db.MainViews.OrderBy(
"{varOne} desc").ToList(); return View(model); }Best regards,
Zhanglong
这篇关于在使用Reflection的LINQ查询中使用字符串值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!