2015-08-19 31 views
1

我有一个REST Web Api端点,它可以接收查询参数。属性变通解决方案中的字典

其中一些查询参数用于生成一个带有内部模型属性的LINQ表达式。例如:

http://api.example.com/scenes?episode=32 

查询参数episode生成LINQ表达式:

s => s.Episode == 32 

哪些属性,以使用用于比较在一个属性被指定的每个查询参数有:

public class SceneQueryData 
{ 
    [PropertyFilter("Episode")] 
    public int? Episode { get; set; } 
} 

我在说:"Hey, use this "episode" query parameter as a filter for the "Episode" property of the model"。现在

,所产生的表达是一个简单的相等比较(=),所以我需要更复杂的操作(<, <=, >, >=)的,用于我可以在属性设置附加构件:

[PropertyFilter("Episode", QueryOperations = new Dictionary<string, QueryOperation>() 
{ 
    { "le", QueryOperation.LessThanOrEquals }, 
    { "lt", QueryOperation.LessThan }, 
    { "ge", QueryOperation.GreaterThanOrEquals }, 
    { "gt", QueryOperation.GreaterThan } 
}] 

这将允许我进行查询,如scenes?episode.le=20,这将被转换为

e => e.Episode <= 20. 

但是,我无法在字典中作为一个属性参数传递,所以我需要另一种方式来做到这一点使用属性

+0

您可以定义从字符串到静态操作的映射,并将允许的操作/字符串列表传递给属性? – Blorgbeard

+0

@Blorgbeard我想到了,但如果每个属性想要有不同的字符串 - >操作映射? –

+0

那他们呢?你正在编写代码..从表面上看,对我来说似乎不太必要。 – Blorgbeard

回答

0

用AttributeUsage定义一个单独的属性(比如OperationAttribute),使AllowMultiple = true。然后用一个单独的OperationAttribute指定您将放入字典中的每个键值对。像这样:

[AttributeUsage(System.AttributeTargets.Property, AllowMultiple = true)] 
public class OperationAttribute : Attribute 
{ 
    public OperationAttribute(string name, QueryOperation op) 
    { 
     ...etc... 
    } 
} 

public class SceneQueryData 
{ 
    [PropertyFilter("Episode")] 
    [Operation("le", QueryOperation.LessThanOrEquals)] 
    [Operation("lt", QueryOperation.LessThan)] 
    [Operation("ge", QueryOperation.GreaterThanOrEquals)] 
    [Operation("gt", QueryOperation.GreaterThan)] 
    public int? Episode { get; set; } 
} 
相关问题