0
     public ActionResult GenerateReport(FormCollection Form)
        {
            var type_id = Form["type_id"];           
            var Start_Date = Form["Start_Date"];

            StringBuilder sb = new StringBuilder();          
            sb.Append("db.contracts.Where(");
            if (!type_id.Equals(null))
            {
                sb.Append("a => a.type_id == type_id");
            }

            if (!Start_Date.Equals(null))
            {
                sb.Append("&& a => a.Start_Date == Start_Date");
            }
            sb.Append(");");
           //here I need to run the query!!
            return View(cm);
        }

如何在 C# 中执行此 LINQ 查询,我只想运行查询并获取结果..

请帮我...

提前致谢...

4

2 回答 2

1

编辑:此答案适用于原始问题内容,​​如何从字符串执行此 LINQ 表达式:

var expression = @"( from a in Assignments
    where a.assignmentID == 1 && a.assignmentID == 4 )
    select new AssignmentModel
    {
        Title = a.Title,
        Description = a.Description
    }).ToList()";

虽然这个答案应该适用于当前问题中生成的字符串,但只有你会注入db.contracts而不是Assignments我在下面解释的那样。


使用@GekaLlaur 建议的编译类的替代方法是将字符串编译为表达式树,这在您编译LINQ 表达式时可能更合适。

这个 SO 帖子(选择的解决方案)中找到的解决方案看起来好像应该为您开箱即用,仅var p = Expression.Parameter(typeof(List<AssignmentModel>), "Assignments");用于描述您的参数。我会用你的具体例子来测试它,但我还没有库(链接在这里)。

于 2013-05-28T14:52:24.073 回答
1

不要这样做。改用谓词生成器!

简而言之,这是 C# 的一个很好的实现: http ://www.albahari.com/nutshell/predicatebuilder.aspx

谓词构建器使用名为 linqkit 的免费库: http ://www.albahari.com/nutshell/linqkit.aspx

这是另一个解决这个主题的 SO question 以及整个事情是 如何工作的 PredicateBuilder 如何工作

于 2013-05-31T13:47:59.650 回答