How can I create a LINQ query when the type of an object is unknown at compile time

I am developing a web user control that can apply filters to a LinqDataSource object. This is a general control, since it must work with an object of a certain type.

The control knows in which field of the object it should work as the next field

    /// <summary>
    /// Method to get compared column from object
    /// </summary>
    public Expression<Func<T, int>> GetColumnMethod;

(I pass it a method that gets the corresponding field from the type of the object)

We are filtering with this code.

... if (selectedValue == "<=") predicate = predicate.And (c => method (c) <= val); if (selectedValue == "<") predicate = predicate.And (c => method (c) <val);

Everything continues until the LINQ to SQL conversion occurs. Then the error "Method" ..... 'does not support translation into SQL.

Of course, the CLR does not know how to do SQL for delegates.

If only C # can compile the expression before translating to SQL, but I don't know how to do it.

Perversions, such as Expression.Compile (no matter how hard I try all day - I can’t remember them all ... nothing helped)

But ... in the runtime, the CLR already knows the type of my object, so he managed to create an SQL statement that has the specified delegate values. But how to do that? God knows.

Help is much appreciated.

+3
source share
4 answers

LINQ to SQL T-SQL. # T-SQL 1 1, , , , LINQ to SQL .

, , . , , , .

+3

. LINQ #, , - LINQ to SQL.

:

" DateTime"

+2

, , Expression.Compile "perversion". , , . , , , Reflector , , , #.

: , SQL, , GetColumnMethod , ?

0

For custom delegates, SQL does not exist. If it method(c)can be expressed as lambda, you can call lambda as a subexpression using Expression.Invoke, but you will need to build the expression tree yourself, like that .

0
source

Source: https://habr.com/ru/post/1702633/


All Articles