2017-08-11 62 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