2009-11-16 43 views
1

我需要將下面的代碼轉換爲一個表達式,我會解釋爲什麼:需要幫助建設的LINQ to SQL表達式

results = results.Where(answer => answer.Question.Wording.Contains(term)); 

結果是IQueryable的<ISurveyAnswer>
問題是ISurveyQuestion
措辭字符串

問題是,問題並不總是LINQ to SQL屬性的名稱。

這會給我的PropertyInfo的實際ISurveyQuestion財產

private static PropertyInfo FindNaturalProperty<TMemberType>(Type search) 
{ 
    IDictionary<string,PropertyInfo> properties = new Dictionary<string,PropertyInfo>(); 

    search.GetProperties().Each(prop => 
    { 
     if (null != prop.PropertyType.GetInterface(typeof(TMemberType).Name)) 
      properties.Add(prop.Name, prop); 
    }); 

    if (properties.Count < 1) throw new ArgumentException(String.Format("{0} has no properties of type {1}", search.Name, typeof(TMemberType).Name)); 
    if (properties.Count == 1) return properties.Values.First(); 

    search.GetInterfaces().Each(inter => 
    { 
     inter.GetProperties().Each(prop => 
     { 
      if (null != prop.PropertyType.GetInterface(typeof(TMemberType).Name)) 
       properties.Remove(prop.Name); 
     }); 
    }); 

    if (properties.Count < 1) throw new ArgumentException(String.Format("{0} has no properties of type {1} that are not members of an interface", search.Name, typeof(TMemberType).Name)); 
    if (properties.Count > 1) throw new AmbiguousMatchException(String.Format("{0} has more than one property that are of type {1} and are not members of an interface", search.Name, typeof(TMemberType).Name)); 


    return properties.Values.First(); 
} 

一旦我擁有的PropertyInfo如何翻譯,爲表達式樹?

編輯:

我基本上需要的是:

results = results.Where(answer => answer.GetQuestionProperty().GetValue(answer).Wording.Contains(term)); 

但是,這並不工作,所以我需要建立表達式樹本人,對LINQ到SQL。

回答

1

閱讀這個問題我認爲你所追求的是動態Linq - 這是一個幫助庫,可以讓你使用字符串動態地(!)建立Linq查詢,而不是在設計時。這意味着如果你能得到你的財產名稱,你應該能夠即時創建你的查詢。

ScottGu有一篇文章here

+0

最後,我倆都在ScottGu的博客:) – Kelsey 2009-11-16 19:42:00

1

什麼你試圖做的是創建一個動態查詢,你想對動作表/屬性查詢是動態的爲好。我不確定這是否很容易根據您想要如何使用它。

退房ScottGu的博客文章: http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx

退房裏克施特拉爾的博客文章: http://www.west-wind.com/Weblog/posts/143814.aspx

+0

啊哈!這絕對看起來像答案。謝謝! 不幸的是,只有一個綠色的複選標記,Murph首先回答:( – 2009-11-16 19:57:57

+0

results.ElementType應該讓我訪問我正在尋找的PropertyInfo。然後DynamicLinq應該爲我構建表達式...我想。 – 2009-11-16 20:07:49