2010-10-21 61 views
1

everyone。 我知道,這個話題已經被討論過了。但不幸的是,我沒有發現在現有的answers.So任何解決方案,我有下面的代碼:LINQ To SQL異常:本地序列無法用於LINQ to SQL實現

public List<List<string>> DataTableParser(IQueryable<T> queriable) 
    { 
     //I missed the unnecessary code 

     return queriable.Select(SelectProperties).ToList(); 

     //I missed the unnecessary code   
    } 

    private Expression<Func<T, List<string>>> SelectProperties 
    { 
     get 
     { 
      var properties = typeof(T).GetProperties(); 
      // 
      return value => properties.Select 
             (
       // empty string is the default property value 
      prop => (prop.GetValue(value, null) ?? string.Empty).ToString() 
             ) 
             .ToList(); 
     } 
    } 

所以,在方法DataTableParser我有下一個消息的異常:
「本地序列除了Contains()運算符「之外,不能用於查詢運算符的LINQ to SQL實現。 我不在我的查詢「where」部分中使用。所以我無法想象如何使用「包含」運算符。我無法理解這個例外的原因。 有沒有人有任何想法?我會感謝任何幫助。謝謝。

+0

什麼是「屬性」變量? – 2010-10-21 08:42:41

+0

對不起,喬恩,我忘了它。我將它添加到代碼中。 var properties = typeof(T).GetProperties(); – Deniplane 2010-10-21 10:05:41

回答

1

嘗試使用

return queriable.AsEnumerable().Select(SelectProperties).ToList(); 

這首先計算可查詢的SQL和內存中的對象,然後將被反射可加工

LINQ僅適用於SQL知道如何表達轉化爲SQL創建。有數量有限的可轉換爲sql的表達式。表示您的列的屬性可以轉換爲sql。

queriable.Select(x=>x.MyColumn); 
//is translatable to sql when there is a column that is named MyColumn in your table 

queriable.Where(x=>x.MyColumn.Contains("X")) 
//is translatable to sql as "...where MyColumn like '%X%' ..." 

queriable.Select(x=> new { x.MyColumn, x.AnotherColumn}) 
//is translatable to sql for selecting multiple columns 

queriable.Select(SelectProperties) 
//is not translatable to sql because it does not return an expression that selects a single value, and its not an expression that returns a new object. 

你打算如何使用這種方法?

+0

你好,蒂翁。謝謝您的回答。我很感激你的例子。他們幫助我理解這個問題。但你的建議「return queriable.AsEnumerable()。Select(SelectProperties).ToList();」沒有幫助我。類型參數不能從使用中推斷出來。 – Deniplane 2010-10-21 17:20:14

+0

你能告訴你如何使用該功能嗎?你通過什麼途徑? – Tion 2010-10-21 17:29:45