解決System.NotSupportedException: Local sequence cannot ... except the Contains() operator.

  • 2961
  • 0

當你嘗試跨DataContext和in-memory data做Linq查詢時,就會遇到
System.NotSupportedException: Local sequence cannot be used in LINQ to SQL implementation of query operators except the Contains() operator.
那要怎麼解決呢?

當你有一個DataContext的查詢和一個memory裡的資料,可能是List<T>,想要把它們用Linq Join成一個資料來源再對它做查詢

就會遇到這個錯誤,錯誤說明是因為它們來自不同的來源,只支援Contains()這一個運算子.

 

List<User> memUsers = new List<User>();
memUsers.add(new User("John"));
memUsers.add(new User("Mary"));

var dcUsers = from user in dataContext
                        select user;

CustomUser[] joinResult = (from dcuser in dcUsers
                              join muser in memUsers
                              on dcuser.name equals muser.name
                              select new {Name = mname.name, Gender = dcuser.gender}).toArray();

//this will have NotSupportException

網路上有人教就用Contains()代替equals來做查詢就可以解決,但不是每個情況都可以這樣解.

但其實有一個解決,因為問題來自他們的來源不同,那只要把來源統一不就解決了嗎?

Linq在你真正使用查詢得到的資料前都不會去取得資料,只會保留一個動態產生的查詢句子.

那麼只要在做Join查詢時加上一個toArray(),就可以把查詢句子變成真正的in-memory 資料,就可以了.

當然這樣子效能可能會變差一點.

 

List<User> memUsers = new List<User>();
memUsers.add(new User("John"));
memUsers.add(new User("Mary"));

var dcUsers = from user in dataContext
                        select user;

CustomUser[] joinResult = (from dcuser in dcUsers.toArray()
                              join muser in memUsers
                              on dcuser.name equals muser.name
                              select new {Name = mname.name, Gender = dcuser.gender}).toArray();

//this works

 

My WP Blog with english technical docs.