Reputation: 20987
I'm writing a dynamic filter for my controllers, where I White list expressions to provide an interface to filter. I have a metadata service which stores the white listed properties in an Dictionary like so:
public class PropertyMetadata<TEntity>
{
public Expression<Func<TEntity, object>> Expression;
public PropertyType PropertyType;
}
public class EntityMetadataService<TEntity> : IEntityMetadataService<TEntity>
{
public Dictionary<string, PropertyMetadata<TEntity>> PropertyMap = new Dictionary<string, PropertyMetadata<TEntity>>();
//Unrelavent information Omitted
}
I'm registering my metadata dictionary like so:
public static Dictionary<string, PropertyMetadata<ServiceRequest>> ServiceRequestMap
{
get
{
return new Dictionary<string, PropertyMetadata<ServiceRequest>> {
{ nameof(ServiceRequest.Id) , new PropertyMetadata<ServiceRequest> { PropertyType = PropertyType.Integer, Expression = x => x.Id } },
{ nameof(ServiceRequest.ConversationId) , new PropertyMetadata<ServiceRequest> { PropertyType = PropertyType.Integer, Expression = x => x.ConversationId } }
};
}
}
public class ServiceRequest
{
public int Id { get; set; }
public int ConversationId { get; set; }
}
When I am dynamically building my query, my property now magically has transformed to have a convert:
var binaryExpression = expressionBuilder(propertyMetadata.Expression.Body, constant);
My property Expression body now contains a convert for some reason
Is there something that I'm missing about these expressions, when I use a string property there is no convert there so why is it appearing for my Integer Properties?
Upvotes: 0
Views: 43
Reputation: 20987
In case anyone was wondering, the reason for this is because string types are already objects, while Int are value types and need to be casted to object
Since my expression is:
public Expression<Func<TEntity, object>> Expression;
When I Initialize a PropertyMap Expression to a string property
Expression = x => x.Name;
The representation would remain while Assigning it to a int property creates an cast automatically
Expression = x => x.Id
is really doing something more like this
Expression = x => (object)x.Id
Upvotes: 1