2013-10-23 48 views
2

的常量值我收到以下錯誤: 異常詳細信息:System.NotSupportedException:無法創建類型爲'FileCombined'的常量值。只有原始類型或枚舉類型在此背景下Linq With Entity Framework錯誤 - 無法創建類型

我使用下面的代碼的支持:

var o1 = new FileCombined(){ ScholarshipID = 3, FileDescription = "smt" }; 
var o2 = new FileCombined() { ScholarshipID = 10, FileDescription = "smt" }; 

List <FileCombined> list = new FileCombined[] { o1, o2 }.ToList(); 

var data = (from scholarship in db.ScholarshipRequests 
      join file in list on scholarship.ScholarshipRequestID equals file.ScholarshipID 
      select new { ScholarshipID = scholarship.ScholarshipRequestID, FileDescription = file.FileDescription }).ToList(); 

如果我改變了LINQ表達的順序,查詢工作正常:

var o1 = new FileCombined(){ ScholarshipID = 3, FileDescription = "smt" }; 
var o2 = new FileCombined() { ScholarshipID = 10, FileDescription = "smt" }; 

List <FileCombined> list = new FileCombined[] { o1, o2 }.ToList(); 

var data = (from file in list 
      join scholarship in db.ScholarshipRequests on file.ScholarshipID equals scholarship.ScholarshipRequestID 
      select new FileCombined(){ ScholarshipID = scholarship.ScholarshipRequestID, FileDescription = file.FileDescription }).ToList(); 

任何人都可以解釋或找到解決方案? 我需要先查詢工作,因爲我在不斷的代碼

+0

連接到數據庫ScholarshipRequests?如果它在第一個代碼示例中,LINQ將嘗試在不知道List 對象的DB上運行查詢。 –

+0

感謝您的解釋。 – kfir

回答

1

假設list有更多複雜的查詢是一個可變的內存,和db.ScholarshipRequests是在上下文中的表,這確實是不可能的。您不能指望EF創建一個將內存集合與數據庫表連接起來的查詢。

可以裝載表在內存中,但請予以警告,這將加載整個表在內存中,它可以/將導致性能問題。

像這樣(我db.ScholarshipRequests後添加.ToList()):

var data = (from scholarship in db.ScholarshipRequests.ToList() 
      join file in list on scholarship.ScholarshipRequestID equals file.ScholarshipID 
      select new { ScholarshipID = scholarship.ScholarshipRequestID, FileDescription = file.FileDescription }).ToList(); 
+0

謝謝,像魔術一樣工作。 – kfir

+0

我會記住內存問題 – kfir

2

要添加到@馬騰的答案,我會說,你也可以刪除加入並使用Contains,因爲在你的情況,你會得到相同的結果(我認爲list不會變得巨大)。然後你可以查找列表中的FileDescription(我可能會創建字典)。

var list2 = list.Select(x => x.ScholarshipID); 
var data = (from scholarship in db.ScholarshipRequests 
      where list2.Contains(scholarship.ScholarshipRequestID) 
      select new { ScholarshipID = scholarship.ScholarshipRequestID }).ToList(); 
// do the lookup in "list" and get result 
+0

謝謝,我會試試看 – kfir

相關問題