I have code generation expressions that need to be passed as the where clause in the database, and I'm trying to speed things up a bit.
In the example below, the where statement matches the PK of the table with the passed value:
private Expression MakeWhereForPK(int id) { var paramExp = Expression.Parameter(typeof(Brand),"b");
The above simplification of the question - the real thing includes code that allows you to get the table for the query and find its PK, etc. This effectively does the same thing you can usually do in code:
ctx.Brands.Where(b => b.ID = id);
This works fine, but while testing to optimize things a bit, I found it rather slow - executing above 1,000,000 times takes about 25 seconds. Itβs better if I omit the last line above (but obviously then itβs useless!), So this is an Expression.Lamba expression that takes about 2/3 times, but the rest is not great either.
If all the queries happened at once, I could turn it into an IN style expression and generate it once, but unfortunately this is not possible, so I hope this saves most of the generation above and just reuse the generated expression, but passing another id value.
Please note that since this will be passed to Linq, I cannot compile the expression to have an integer parameter that I can pass on the call - it should remain as an expression tree.
Thus, the following task may be a simple version for performing synchronization exercises:
Expression<Func<Brand,bool>> savedExp; private Expression MakeWhereForPKWithCache(int id) { if (savedExp == null) { savedExp = MakeWhereForPK(id); } else { var body = (BinaryExpression)savedExp.Body; var rightExp = (ConstantExpression)body.Right;
How can I reuse an expression just with a different id value?