2010-07-23 140 views
6
public ActionResult ReadXMLDevices(int groupID) 
{    
    var query = from k in XMLEntities.unassigneditems 
    where k.DevOrAcc == true && k.Group == groupID 
    select k; 

    var view_query = from i in query 
        select new GetFreeDevices 
        { 
         MArticleNumber = i.ArticleNumber, 
         MFirmware = i.Firmware, 
         MGroup = i.Group, 
         MName = i.Name, 
         MSoftware = i.SoftwareVersion, 
         SA = GetNumberOfDevices(i.ArticleNumber,2), 
         STH = GetNumberOfDevices(i.ArticleNumber,3), 
         SASTH = GetNumberOfDevices(i.ArticleNumber,7) 
        }; 
    return PartialView(view_query); 
} 

public int GetNumberOfDevices(string artNo,int loc) 
{ 
    var num_dev = (from k in XMLEntities.deviceview 
        where k.Reserved == false && k.Sold == false && k.LocationNameId == loc && k.ArticleNumber == artNo 
        select k).Count(); 
    return num_dev; 
} 

錯誤:LINQ到實體無法識別方法「的Int32

LINQ to Entities does not recognize the method 'Int32 GetNumberOfDevices(System.String, Int32)' method, and this method cannot be translated into a store expression. How to resolve this???

回答

8

可以分成兩部分,你的查詢,以確保該列表是在內存中調用GetNumberOfDevices()方法之前。您可以通過將結果轉換爲List或在此例中爲List<GetFreeDevices>來查詢內存。這樣一來,LinQ to Entities不需要對XML進行任何翻譯,您可以使用您的GetNumberOfDevices()方法。

var view_query = (from i in query 
    select new GetFreeDevices 
    { 
     MArticleNumber = i.ArticleNumber, 
     MFirmware = i.Firmware, 
     MGroup = i.Group, 
     MName = i.Name, 
     MSoftware = i.SoftwareVersion 

    }).ToList(); 
var result_query = from i in query 
    select new GetFreeDevices 
    { 
     MArticleNumber = i.MArticleNumber, 
     MFirmware = i.MFirmware, 
     MGroup = i.MGroup, 
     MName = i.MName, 
     MSoftware = i.MSoftware, 
     SA = GetNumberOfDevices(i.MArticleNumber,2), 
     STH = GetNumberOfDevices(i.MArticleNumber,3), 
     SASTH = GetNumberOfDevices(i.MArticleNumber,7) 
    }; 
return PartialView(result_query); 

請注意最後一條語句需要PartialView接受列表或IEnumerable而不是IQueryable

0

還有另一種簡單的方法。

首先,將數據加載從數據庫中存儲:

// ... 
var query_view = from i in query 
       select i; 

query_view.Load(); 
// ... 

然後,做任何你想要使用LINQ到對象,不是L2E:

var view_query_1 = from i in DbContext.myEntities.Local 
       select new GetFreeDevices 
       { 
        MArticleNumber = i.ArticleNumber, 
        MFirmware = i.Firmware, 
        MGroup = i.Group, 
        MName = i.Name, 
        MSoftware = i.SoftwareVersion, 
        SA = GetNumberOfDevices(i.ArticleNumber,2), // 
        STH = GetNumberOfDevices(i.ArticleNumber,3), // These are now ok! 
        SASTH = GetNumberOfDevices(i.ArticleNumber,7) // 
       }; 
    return PartialView(view_query_1.AsEnumerable()); 

您可以使用這一招的L2E不支持的任何方法。

相關問題