2012-01-16 107 views
7

我有一個名爲new_trexmail的實體,名爲new_contextline。相當於SQL IN子句

我想獲得一個實體列表,其中new_contextlineis在一個定義列表中。

下面的代碼失敗,出現錯誤:NotSupportedException: Invalid 'where' condition. An entity member is invoking an invalid property or method.

string[] test = new[]{"aaa", "hhh"}; 

var query = from n in New_trexmailSet 
      where test.Contains(n.New_contextline) 
      select n; 

我明白爲什麼被拋出這個錯誤,但我不知道是否有可能做使用XRM IN子句的equiavalent。

如果可能的話,我該如何去讓XRM執行SELECT * FROM new_trexmail WHERE new_contextline in ('aaa', 'hhh')

謝謝,

大衛

回答

5

檢查出(長於期望的)list of LINQ limitations,特別是在where條款的限制:

該條的左側必須是一個屬性名稱條款的右邊 必須是一個值。您不能將左側設置爲 常量。子句的兩邊不能是常量。支持 字符串函數Contains,StartsWith,EndsWith和Equals。

因此,由於test不是CRM屬性,因此不能對其調用Contains。然而,圍繞這一方法是使用「Dynamic Linq」由ScottGu開發,如下面所示:

//must include the below using statements 
//using System.Linq; 
//using System.Linq.Dynamic; 

var trexmailSet = New_trexmailSet; 

string[] test = new[] { "aaa", "hhh" }; 

string whereClause = ""; 

foreach (string name in test) 
{ 
    whereClause += string.Format("new_contextline = \"{0}\" OR ", name); 
} 

trexmailSet = trexmailSet.Where(whereClause.Substring(0, whereClause.Length - 4)); 

var query = from n in trexmailSet 
      select n; 
+0

,沒有工作!我不知道那個庫,它看起來很有用。非常感謝。 – dlarkin77 2012-01-17 10:03:09