2010-11-17 69 views
0

這在我看來,這是很難...LINQ從外部方法SQL訂購

var MostRated = (from p in db.Posts 
           let AverageRating = CalculateAverageRatingFromPost(p) 
           where p.PostStatus == Convert.ToInt32(PostStatusEnum.Published.Value) && p.IsDeleted == false 
           orderby p.PublishedDate descending 
           select new 
           { 
            PostUrl = Common.PostUrl(p.Section.Name, p.Permalink), 
            Title = Common.TrimString(p.Title, 50), 
            Excerpt = Common.TrimString(p.Excerpt, 80), 
            AverageRate = CalculateAverageRating((from pr in db.Ratings 
                where pr.ObjectType == Convert.ToInt32(ObjectTypeEnum.Post.Value) && pr.ObjectID == p.ID 
                select pr).SingleOrDefault()), 
            PublishedDate = new DateHelper().DateTimeInWords(p.PublishedDate.Value) 
           }).OrderByDescending(o => o.AverageRate).Take(5).ToList(); 

而另一種方法是

private Decimal CalculateAverageRating(Rating pr) 
     { 
      if (pr != null) 
      { 
       Decimal Average = ((1 * (Decimal)pr.Star1) + (2 * (Decimal)pr.Star2) + (3 * (Decimal)pr.Star3) + (4 * (Decimal)pr.Star4) + (5 * (Decimal)pr.Star5))/((Decimal)pr.Star1 + (Decimal)pr.Star2 + (Decimal)pr.Star3 + (Decimal)pr.Star4 + (Decimal)pr.Star5); 
       return Average; 
      } 
      else 
      { 
       return 0; 
      } 
     } 

我得到這個運行時錯誤「不支持翻譯到SQL「。

我想要的是獲取帖子的列表,並做一個小的快速計算的評級,然後排序從最高到最低的只有5個職位。

謝謝

回答

1

我還沒有測試過這個,但嘗試將函數定義爲Expression對象。

Expression<Rating, Decimal> CalculateAverageRating = 
    pr => (Decimal)(
     pr == null ? 0 : 
     (pr.Star1 + 2*pr.Star2 + 3*pr.Star3 + 4*pr.Star4 + 5*pr.Star5) 
     /(pr.Star1 + pr.Star2 + pr.Star3 + pr.Star4 + pr.Star5)); 
+0

我試圖說明這一點,但沒有工作...表達式只帶有一個參數...表達式 Taha 2010-11-18 15:28:27