2009-10-23 27 views
0

我不完全確定標題的措辭正確,但這裏的情況......我今天注意到,當試圖爲Linq創建一個通用保存函數時Sql,當我使用lambda對數據上下文選擇。它在具有另一個通用接口的類型約束的泛型函數中斷開。但是,它使用LINQ語法正常工作。我或多或少地提出這個問題來理解爲什麼會發生這種情況。NotSupportedException對一個DataContext使用lambda和一個接口的泛型函數約束

被引發的異常是:
NotSupportedException異常
接口構件IEntity`1.ID的映射不被支持。

所涉及的代碼類似於此(簡化):
錯誤造成的功能是GenericFunc <牛逼>

 

//Assume SomeTable is generated from a DBML L2S file. 

//partial extension of the L2S class 
public partial class SomeTable : IEntity<SomeTable> { } 

//interface to expose shared properties in these entity classes 
public interface IEntity<T> where T : class 
{ 
    //isolated application, int Primary key for all these tables. 
    int ID { get; set; } 
} 

//simple helper class for L2S stuff. 
public class Repository 
{ 
    //helper for inserting/updating data.. 
    public void SaveSomeTable(SomeTable data) 
    { 
     SomeDataContext db = new SomeDataContext(); 
     GenericFunc<SomeTable>(db.SomeTables, data); 
    } 

    //toy function for this example 
    public void GenericFunc<T>(System.Data.Linq.Table<T> table, T data) where T : class, IEntity<T>, new() 
    { 
     //note the generic type constraints... 
     //in this case, all table entities conform to the IEntity<T> class. 

     //breaks 
     var row = table.SingleOrDefault(o => o.ID == data.ID); 

     //works 
     var row1 = (from item in table where item.ID == data.ID select item).SingleOrDefault(); 

     //... more stuff. 
    } 
} 

回答

1

這是不是一個真正的拉姆達問題。這裏也是非查詢語法:

var row1 = table.Where(o => o.ID == data.ID) 
       .SingleOrDefault(); 

基本上,它編譯爲與查詢表達式相同的代碼。

我強烈懷疑這是SingleOrDefault(內部)的不同代碼路徑,這會產生問題。

+0

doh!哈!我甚至沒有注意到我正在那樣做。我正在比較蘋果和橘子。無論如何,奇怪的是SingleOrDefault的謂詞會導致這個問題。我認爲你是對的,這是該功能的內在。謝謝! – Nathan 2009-10-23 21:02:54

相關問題