2017-08-11 60 views
0

我正在为我的控制器写一个动态过滤器,其中我提供了一个过滤器接口的白名单表达式。我有一个存储白色列出的属性在字典像这样一个元数据服务:指向属性的表达式神奇地有一个转换

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 
} 

我登记我的元数据字典,像这样:

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; } 
} 

当我动态构建我的查询,我的属性现在已经奇迹般地被转化为具有一个转换:

var binaryExpression = expressionBuilder(propertyMetadata.Expression.Body, constant); 

我的财产表达的身体现在包含某种原因

皈依

enter image description here

有没有办法,我缺少这些东西的表达,当我使用的字符串属性没有转换有那么为什么它显示我的整数属性?

回答

1

如果有人想知道,这样做的原因是因为字符串类型已经是对象,而诚信是值类型,需要强制转换为对象

因为我的表达是:

public Expression<Func<TEntity, object>> Expression; 

当我初始化属性映射到表达一个字符串属性

Expression = x => x.Name; 

,而其分配给一个int属性的表示将继续创建投自动

Expression = x => x.Id 

真的做得更多的东西像这样

Expression = x => (object)x.Id