I asked a very similar question yesterday, but it wasn't until today I realised the answer I accepted doesn't solve all my problems. I have the following code:
public Expression<Func<TItem, object>> SelectExpression<TItem>(string fieldName)
{
var param = Expression.Parameter(typeof(TItem), "item");
var field = Expression.Property(param, fieldName);
return Expression.Lambda<Func<TItem, object>>(field,
new ParameterExpression[] { param });
}
Which is used as follows:
string primaryKey = _map.GetPrimaryKeys(typeof(TOriginator)).Single();
var primaryKeyExpression = SelectExpression<TOriginator>(primaryKey);
var primaryKeyResults = query.Select(primaryKeyExpression).ToList();
This allows me to pull out the primary keys from an IQueryable<TUnknown>
. The problem is that this code only works with a single primary key and I need to add support for multiple PKs.
So, is there any way I can adapt the SelectExpression
method above to take an IEnumerable<string>
(which is my list of primary key property names) and have the method return an expression that selects those keys?
I.e. Given the following:
var knownRuntimePrimaryKeys = new string[] { "CustomerId", "OrderId" }`
My Select needs to do the following (at runtime):
var primaryKeys = query.Select(x=> new { x.CustomerId, x.OrderId });
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…