Mukarram
Mukarram

Reputation: 115

How to Execute String formatted LINQ query in c# MVC3

     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);
        }

How can i execute this LINQ query in C#, I just want to run the query and get the results..

Please help me...

Thanks in Advance...

Upvotes: 0

Views: 3541

Answers (2)

amhed
amhed

Reputation: 3659

Don't do this. Use a Predicate Builder instead!

Here is a great implementation from C# in a nutshell: http://www.albahari.com/nutshell/predicatebuilder.aspx

The predicate builder uses a free library called linqkit: http://www.albahari.com/nutshell/linqkit.aspx

Here is another SO question that addresses this topic and how the whole thing works How does PredicateBuilder work

Upvotes: 1

Dead.Rabit
Dead.Rabit

Reputation: 1975

EDIT: this answer works with the original question content, how to execute this LINQ expression from a string:

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

though this answer should work with the generated string in the current question, only you would be injecting db.contracts rather than Assignments as I explain below.


The alternative to using the compilation classes as @GekaLlaur suggests is to compile the string into an Expression tree, which is possibly more appropriate here as you're compiling LINQ expressions.

The solution found in this SO post (Chosen Solution) looks as though it should work out of the box for you, only using var p = Expression.Parameter(typeof(List<AssignmentModel>), "Assignments"); to describe your parameter. I would test it with your specific example but I don't already have the libraries (linked here).

Upvotes: 1

Related Questions