类型'System.Linq.Queryable'上没有泛型方法'Where'与提供的类型参数和参数兼容

问题描述 投票:1回答:2

我想使用IQueryable检索特定记录。但我得到错误'没有通用方法'其中'on type'System.Linq.Queryable'与提供的类型参数和参数兼容。如果方法是非泛型的,则不应提供类型参数。'。我得到了所选的行ID,但我无法显示它。这是我的代码。

 internal static IQueryable GetRecordsFromPrimaryKeys(this IQueryable datasource, List<FilterDescriptor> primaryKeys)
    {
        IQueryable data = datasource;

        ParameterExpression paramExp = null;
        bool firstLoop = false;
        System.Linq.Expressions.Expression predicate = null;

        var RecordType = datasource.GetObjectType();
        paramExp = RecordType.Parameter();

        foreach (FilterDescriptor primaryKey in primaryKeys)
        {
            if (!(firstLoop))
            {
                predicate = data.Predicate(paramExp, primaryKey.ColumnName, primaryKey.Value, FilterType.Equals, false, RecordType);
                firstLoop = true;
            }
            else
            {
                predicate = predicate.AndPredicate(data.Predicate(paramExp, primaryKey.ColumnName, primaryKey.Value, FilterType.Equals, false, RecordType));
            }
        }

        if (paramExp != null && predicate != null)
        {
            var lambda = Expression.Lambda(predicate, paramExp);
            data = data.Provider.CreateQuery(
                       Expression.Call(
                       typeof(Queryable),
                       "Where",
                       new Type[] { data.ElementType },
                       data.Expression,
                       lambda
                       )
                   );

        }

        return data;
    }

我的代码适用于IEnumerable / IQueryable / ICollection。但是当我使用关键字virtual指定类并输入ICollection时,它会引发异常。我的代码是

public class RoomType
{
    public int ID { get; set; }

    [MaxLength(10, ErrorMessage = "Room code cannot be longer than 10 characters.")]
    public string Code { get; set; }

    [MaxLength(50, ErrorMessage = "Room name cannot be longer than 50 characters.")]
    public string Name { get; set; }

    public virtual ICollection<RoomCategory> RoomCategories { get; set; }
}

使用关键字“virtual”时,一些随机值会附加到“RecordType”。我认为这会导致异常。仍在寻找解决方案。

我不知道出了什么问题。欢迎任何建议。

谢谢。

linq iqueryable
2个回答
1
投票

我刚遇到类似的情况。问题源于这样一个事实:在某些情况下,您处理的是“代理”,而不是实际的实体。所以,你想确保RecordType匹配data.ElementType

尝试:

var recordType = datasource.GetObjectType();

// make sure we have the correct type (not the proxy)
if (recordType.BaseType.Name != "Object") 
    recordType = recordType.BaseType;

或者更好的是,尝试:

var recordType = data.ElementType

0
投票

尝试使用typeof(Enumerable)而不是typeof(Queryable)

© www.soinside.com 2019 - 2024. All rights reserved.