LINQ to SQL从外部方法订购

时间:2010-11-17 10:00:24

标签: asp.net linq-to-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 个答案:

答案 0 :(得分: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));