2012-10-08 80 views
0

我試圖用信息窗口在谷歌地圖上映射各種標記。直到我嘗試通過控制器傳遞一個字符串時,它一切正常。字符串linq實體錯誤 - json

我得到的錯誤如下:「LINQ實體無法識別方法‘System.String GetMainPhoto(的Int32)’方法,和這種方法不能被翻譯成存儲表述」

我讀過這主要是因爲ToString方法或其他一些方法無法使用而導致的。但是,在這種情況下,我不確定如何糾正這個錯誤。

基本上,我有一個數據庫 - PropertyPhoto保存圖片的文件名。 GetMainPhoto基本上查找所有行並返回主圖片文件名。

public string GetMainPhoto(int id) 
     { 
      return db.PropertyPhotos.Single(p => p.PropertyId == id && p.MainPic == true).PhotoLocation; 

     } 

控制器如下:

public ActionResult Map() 
     { 
      if (Request.IsAjaxRequest()) 
      { 
       var properties = websiteRepository.FindAllProperties(); 

       var jsonProperties = from property in properties 
            select new JsonProperty 
            { 
             PropertyId = property.PropertyId, 
             NoOfBedroom = property.NoOfBedrooms, 
             Price = property.Price, 
             Address1 = property.PropertyAddress.Address1, 
             MainPicSrc = websiteRepository.GetMainPhoto(property.PropertyId), 
             Latitude = property.PropertyAddress.Latitude, 
             Longitude = property.PropertyAddress.Longitude 
            }; 

       return Json(jsonProperties.ToList(), JsonRequestBehavior.AllowGet); 
      } 
      else 
      { 
       return View(); 
      } 
     } 

回答

2

嘗試急切地伸入一個匿名類型之前調用.ToList()首先加載數據,否則EF不知道怎麼翻譯的websiteRepository.GetMainPhoto調用SQL :

var properties = websiteRepository.FindAllProperties().ToList(); 

但要小心。通過這樣做,您可能會遇到SELECT N+1 problem,因爲對於初始結果集的每個元素,您將發送SQL查詢以獲取MainPicSrc屬性。

更好的方法是直接由數據庫執行此join,並且不要使用websiteRepository.GetMainPhoto調用。