Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute String as a Linq

Is there a way I can execute a String as a Linq? I had a dynamci query and for that I had to convert the Linq expression into string, then append string bulider which has some conditional query. So whole expression is now in string. How to execute this string now? Should I again convert this string to Linq? How to proceed?

 StringBuilder sb = new StringBuilder();
 if (InstId != String.Empty)
 {
     sb.Append("application.Id ==" + InstId);
 }
 if (BId != String.Empty)
 {
     sb.Append("&& application.BId ==" + BId);
 }
 if (CId != String.Empty)
 {
     sb.Append("&& application.CId ==" + CId);
 }

String query=("from tables in context.Application .........
........join .........."+sb);

var q1=query;

Now how to execute this q1?

like image 717
JulyOrdinary Avatar asked May 09 '26 14:05

JulyOrdinary


2 Answers

You don't need StringBuilder for that:

var query = context.Application;

if (InstId != String.Empty)
{
    query = query.Where(a => a.Id == InstId);
}
if (BId != String.Empty)
{
    query = query.Where(a => a.BId == BId);
}
if (CId != String.Empty)
{
    query = query.Where(a => a.CId == CId);
}

var items = query.Join(/* your join here */).ToList();

Query won't be executed untill ToList or other methods like that is invoked, so you can append Where() as long you'd like to.

like image 51
MarcinJuraszek Avatar answered May 12 '26 12:05

MarcinJuraszek


While I don't necessarily think it's a great practice in a lot of cases, there is a Dynamic LINQ library that allows you to do just that.

In general, if possible, I'd recommend using something that can be more strongly type checked, such as @MarcinJuraszak's response or something like a PredicateBuilder class.

like image 45
goric Avatar answered May 12 '26 12:05

goric



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!