Maki92
Maki92

Reputation: 441

LINQ Entity Framework Variable to select db Column

does anyone know how do I query a variable to select a column name of a table? Example is given as below. Instead of Select(x => x.ColumnName), I would like to Select(field).

public bool isFound(string field, int id)
{ 
    db.Table.Where(x => x.tableID == id).Select(field).First();

    return;
}

Upvotes: 1

Views: 1210

Answers (3)

Palanikumar
Palanikumar

Reputation: 7150

Try this,

string field = "tableID";
ParameterExpression param = Expression.Parameter(typeof(Table), "x");
MemberExpression propExpression = Expression.PropertyOrField(param, field);
Expression<Func<Table, string>> selector = Expression.Lambda<Func<Table, string>>(propExpression, param);
var result = db.Table.Select(selector).First();

Or Use Nuget package DotNetHelper - https://www.nuget.org/packages/DotNetHelper/

Install-Package DotNetHelper

-

var result = db.users.SelectFirst<Table, string>("Name");

Upvotes: 1

JP Lee
JP Lee

Reputation: 53

Have a look at the dynamic linq library:

https://www.nuget.org/packages/System.Linq.Dynamic.Library/

I have a project where I return a list of distinct values from a specified column as follows:

    public static List<string> GetValuesFromDB(string column)
    {

        GradInfoEntities db = new GradInfoEntities();
        //if i pass the column name in it doesn't work
        //i suspect that if i pass as param, it gets quoted coz i'm passing in the value, not the column
        var temp = db.Grads.Where(string.Format("{0} != null", column)).Select(column);

        List<string> result = temp.Cast<string>().ToList();
        return result;
    }

The Dyamanic Linq Library adds overloads for where and select (and a few others, but I've only used those two) that allow you to specify which columns you want to select via a passed in variable.

I've snipped out the sorting and distinct call, but basically I'm returning a string list of all values that aren't null from the passed in column

Edit: I've just checked and there is no First(), but there is a Take(), and an Any()

Upvotes: 0

Mark
Mark

Reputation: 981

This is completely untested and I'm not sure its a thing, but could you create a templated extension method?

public static IQueryable<T> Select(this IQueryable<T> list, string field)
{
    // Create an Expression and find the property field
    ParameterExpression pe = Expression.Parameter(typeof(string), field);

    // Apply the Expression to the IQueryable
}

Here's a link with some expression creation:

https://msdn.microsoft.com/en-us/library/Bb882637.aspx

Upvotes: 0

Related Questions