2015-11-08 83 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; 
    } 
} 

注意,它將無法正常使用複雜類型的工作。