I currently have method that create a Expression based on a Generic and one of its property, using reflection
For exemple, this works.
var myVar = 1;
var property = typeof( TEntity ).GetProperty( "SomeId" );
query = query.Where( PropertyEquals<TEntity, int>( property, myVar ) );
Here's the PropertyEquals definition
private Expression<Func<TItem, bool>> PropertyEquals<TItem, TValue> ( PropertyInfo property, TValue value ) {
var param = Expression.Parameter( typeof( TItem ) );
var memberExp = Expression.Property( param, property );
BinaryExpression body;
//If nullable, Expression.Equal won't work even if the value is not null. So we convert to non nullable (the compared expression)
Type typeIfNullable = Nullable.GetUnderlyingType( memberExp.Type );
if ( typeIfNullable != null ) {
var convertedExp = Expression.Convert( memberExp, Expression.Constant( value ).Type );
body = Expression.Equal( convertedExp, Expression.Constant( value ) );
} else {
body = Expression.Equal( memberExp, Expression.Constant( value ) );
}
return Expression.Lambda<Func<TItem, bool>>( body, param );
}
It returns something like
x => x.SomeId == myVar
But, I'm looking to do the same thing, but to get something like
x => ids.Contains( x.Id )
How should I create a method like PropertyContainedIn?
Aucun commentaire:
Enregistrer un commentaire