简体   繁体   中英

Linq select with column name

I want to select with column name from table with LINQ Basically I want select only single column records from a table with Column Name

this is what i have used so far

public static IQueryable<T> SelectByField<T>(this IQueryable<T> q, string ColumnName)
    {
        var param = Expression.Parameter(typeof(T), "p");
        var prop = Expression.Property(param, ColumnName);
        var exp = Expression.Lambda(prop, param);
        string method = "Select";
        Type[] types = new Type[] { q.ElementType, exp.Body.Type };
        var mce = Expression.Call(typeof(Queryable), method, types, q.Expression, exp);
        return q.Provider.CreateQuery<T>(mce);
    }

I am getting following error

Unable to cast object of type 'System.Data.Entity.Infrastructure.DbQuery 1[System.String]' to type 'System.Linq.IQueryable 1'.

I tried above method with reference to following method

public static IQueryable<T> OrderByField<T>(this IQueryable<T> q, string SortField, bool Ascending)
    {
        var param = Expression.Parameter(typeof(T), "p");
        var prop = Expression.Property(param, SortField);
        var exp = Expression.Lambda(prop, param);
        string method = Ascending ? "OrderBy" : "OrderByDescending";
        Type[] types = new Type[] { q.ElementType, exp.Body.Type };
        var mce = Expression.Call(typeof(Queryable), method, types, q.Expression, exp);
        return q.Provider.CreateQuery<T>(mce);
    }

you can use dynamic library which will allow you to build a dynamic where clause with Linq

check these links:

Link to install the dynamic library

Scott Gu examples

regards

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM