LINQ to SQL,获取给定ID的最新记录

时间:2010-08-19 04:13:10

标签: c# linq-to-sql

intHi,

LINQ很新。

我有一张评级表 用户为实体添加一组评级 每个用户的实体可以有多个评级集。

例如,假设实体是一辆汽车。该车的外观和性能评级。用户可以不止一次评估给定汽车的外观和性能。所以我的表看起来像这样(评级字段不是一个标识列;它是一个比例为1 - 10的int):

ReviewID     UserID     EntityID     CatID     Rating    Body               DateSubmitted
1            3          6            1         7         "drives great"     8/01/2010 02:36:28 PM
2            3          6            2         8         "looks great"      8/01/2010 02:36:28 PM
3            3          6            1         2         "broke down"       8/18/2010 11:39:58 PM
4            3          6            2         1         "paint flaked off" 8/18/2010 11:39:58 PM

现在,我有一个帮助方法,我提供UserID和EntityID,我想返回最新的评级集(进入包含评级类别的ViewModel)。

public static IQueryable<RatingViewModel> GetRatingViewModel(int EntityID, int UserID)
    {
        DB _db = new DB();

        var a =

            from rating in _db.Ratings
            join ratingCat in _db.RatingCategories
                on rating.RatingCategoryID equals ratingCat.RatingCategoryID
            where rating.UserID == UserID
                && rating.EntityID == EntityID
            select new RatingViewModel
             {
                 Rater = rating.User,
                 RaterRating = rating,
                 RatingCategory = ratingCat

             };

        return a;
    }

我需要添加什么样的“where”或“group by”或“order by”才能获取给定UserID和EntityID的最新评级集?

谢谢!

2 个答案:

答案 0 :(得分:0)

考虑通过DateSubmitted对方法的返回进行排序,然后获取您想要的条目数。

var a = from rating in _db.Ratings
        join ratingCat in _db.RatingCategories
            on rating.RatingCategoryID equals ratingCat.RatingCategoryID
        where rating.UserID == UserID
            && rating.EntityID == EntityID
        orderby rating.DateSubmitted descending

        select new RatingViewModel
         {
             Rater = rating.User,
             RaterRating = rating,
             RatingCategory = ratingCat

         }
         .Take(10);

答案 1 :(得分:0)

.OrderByDescending(a => a.DateSubmitted).FirstOrDefault()