简体   繁体   中英

Linq Selector with dynamic property name

I have an IQueryable<TEntity> where TEntity is another class BaseEntity<TKey, TUId> .

Because BaseEntity<TKey, TUid> have two generic parameters, I must know TKey and TUId types in advance if I want to select a column from the IQueryable .

But I also know that BaseEntity<TKey, TUId> will always have a numeric property named UId , and that is what I need to get.

What I´m trying to achieve is something like the following code, where I can define a selector variable with the property I want the query to select, but dynamically. Like setting this name in a string variable.

var selector = nameof(BaseEntity<,>.UId);
IQueryable<TEntity> query = GetQueryByPrimaryKey();
var entityUId = Convert.ToInt64(query.Select(selector).Single());

Having a constraint in the TEntity to accept only BaseEntity<TKey, TUId> is not an option, because I don´t have the Type of every parameter, and I would need to define every possibility.

Is there any way to create a dynamic lambda selector to indicate the string name of the property I want to get?

The main objetive is to perform a single query to the database using the primary key and select only one field (the mapped UId column) to improve performance.

I have read some solutions and some pointed out Dynamic Query, but I prefer a native solution.

Looks like you want to create a dynamic expression and call Select on it:

private Expression<Func<BaseEntity<TKey, TUId>, long>> CreateUIdExpression<TKey,
 TUId>()
{
    var param = Expression.Parameter(typeof(BaseEntity<TKey, TUId>));
    var memberExpression = Expression.Property(param, "UId");
    var expr = Expression.Lambda<Func<BaseEntity<TKey, TUId>, long>>(memberExpression, param);

    return expr;
}

Usage:

var newQuery = query.Select(CreateUIdExpression<TKey, TUId>());

BTW, I've assumed that UId is a long.

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