Answer the question
In order to leave comments, you need to log in
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;
}
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question