This question has the same context as that one. I'm copy-pasting the exposition part because it's relevant for both:
We have a project that uses legacy databases with which EntityFramework does not work.
So we have started building a poor-man EntityFramework, with a base class CustomBaseTable
from which entity classes derive. Another class, CustomQueryBuilder
, has methods that build SQL queries : BuildSelectQuery(CustomBaseTable p_objEntity)
and so on.
Our first version builds queries quite nicely, but we're using rather crude objects that aren't really flexible (details withheld to save space).
I recently realized that using Expression
objects would be much more efficient and flexible.
So I'd like to add a method to CustomBaseTable
, that would work more or less like Where()
:
EntityTable z_objEntity = new EntityTable();
z_objEntity.CustomWhere(t => t.Field1 == Value1);
CustomQueryBuilder z_objBuilder = new CustomQueryBuilder(DBTypeEnum.DataBaseType);
string z_strQuery = z_objBuilder.BuildSelectQuery(z_objEntity);
End exposition.
I want CustomWhere()
to store that expression in a property and use the latter in BuildSelectQuery(CustomBaseTable p_objEntity)
, to parse it into a keen SQL Where clause. (Of course it'll happen in a separate method that Update
and Delete
queries will use too.)
I've written a property in CustomBaseTable
:
public Expression<Func<CustomBaseTable, bool>> WhereClauseExpression
So CustomWhere()
should do something like
public static void CustomWhere<T>(this T z_objTable, Expression<Func<T, bool>> p_expWhereClause) where T : CustomBaseTable
{
z_objTable.WhereClauseExpression = p_expWhereClause;
}
However, p_expWhereClause
, being a Expression<Func<T, bool>>
object, can't be converted to Expression<Func<CustomBaseTable, bool>>
.
I've tried creating an ICustomBaseTable
from which CustomBaseTable
derives and make WhereClauseExpression
a Expression<Func<ICustomBaseTable, bool>>
, with the same results.
Inspired by this question, I tried
z_objTable.WhereClauseExpression = LambdaExpression.Lambda<Func<CustomBaseTable, bool>>(p_expWhereClause.Body, p_expWhereClause.Parameters);
Again, the conversion failed.
I don't think I can make WhereClauseExpression
a Expression<Func<T, bool>>
without declaring T
in CustomBaseTable<T>
, which I don't want either.
Of course, a workaround is to have a method in CustomQueryBuilder
that parses the expression into a Where clause, then store the latter in a WhereClause
String
property, but I'd rather generate all the SQL code in one go; it strikes me as cleaner.
Is there a way to store that Expression
into a property, that will work for any derived class?