R
R
Ruslan2015-01-02 15:38:45
C++ / C#
Ruslan, 2015-01-02 15:38:45

Why does a typed IQueryable have a Where(Single,...) method while an untyped one does not?

Hello.
There is a task: searching for an entity by primary key using Linq.
I am trying to do this through dynamic Linq. There is a method that works fine:

public object GetObject<T>(IQueryable<T> data, string pk)
        {
            Type t = data.ElementType;
            PropertyInfo key = GetKeyField(t);//получаем ключевое поле
            object pkvalue = ConvertParameter(key.PropertyType, pk);//конвертируем входной ключевой параметр к типу ключа
            ParameterExpression pe = Expression.Parameter(t);
            Expression left = Expression.PropertyOrField(pe, key.Name);//pe.keyName
            Expression right = Expression.Constant(pkvalue);//pkvalue
            Expression eq = Expression.Equal(left, right);
            Expression<Func<T, bool>> expr = Expression.Lambda<Func<T, bool>>(eq, pe);
            var result = data.Single(expr);
            return result;
        }

This method works fine because we specify the type when calling, when compiling for each typed call, its own overloaded method is created, and each such method is called for its own case.
But I need to make a method that will work with a collection of any type, and this is where the problem arises:
If I use an untyped IQueryable as an input parameter, then I will not be able to call the Single method on the data variable. for some reason it's not there.
How is it possible, after all, to search for an element of a collection by a dynamic condition?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vasily Samoilov, 2015-01-04
@Imagio

What type of element should be returned from the Single() method?
If object , then you can try like this: data.Cast().Single();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question