2015-11-08 112 views
0

可以说,我有一个规则表中与此结构的SQL数据库:匹配条件

Rule   Conditions         Action 
------------`------------------------------------------ --------------------- 
1   {"country": "USA", "state": "NY"}   DoActionOne 
2   {"country": "France", "department": "55"} DoActionTwo 

这些规则适用于我的用户。所以州,国家,部门是我可以在我的用户或用户地址定义中找到的属性。但是这些规则可能是别的。它可以是创建用户的日期,也可以是我现在不期望的内容。

我如何可以加载这个条件串并评估每个规则,与我的用户每个条件?我知道如何从我的数据库中检索数据。我使用实体框架,但我不知道如何转换查询或JSON对象中的字符串。

'NOT TESTED 
For Each rule As Rule In dbContext.rules 
    'Load condition one 
    Dim condition = rule.Conditions.??? 
    If (MyUser[condition.Name] = condition.Value) 
     ' DoAction 
    End If 
Next 

回答

0

您可以使用一点点Reflection来实现这一点。

假设这是你的UserAddress

public class UserAddress 
{ 
    public string Country { get; set; } 
    public string State { get; set; } 
    public int Department { get; set; } 
    //other properties 
} 

然后,假设您已经阅读JSON正确,得到了的规则对字符串(如“国家” &“法国”,“部门名单“&‘55’等),您可以编写规则检查代码

var userAdd = new UserAddress { Country = "France", Department = 55, State = "SomeState" }; 
bool allRulesChecked = true; 
foreach (var rule in rules) 
{ 
    var property = typeof(UserAddress).GetProperty(rule.Key, System.Reflection.BindingFlags.IgnoreCase | 
           System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Instance); 
    if (property != null && property.GetValue(userAdd).ToString() != rule.Value.ToString()) 
    { 
     allRulesChecked = false; 
     break; 
    } 
} 

注意,它将无法正常使用复杂类型的工作。