[英]LINQ to SQL, get most recent records for given ID
intHi, 诠释
Pretty new to LINQ. LINQ的新手。
I have a Ratings table. 我有一个评分表。
A User adds a set of Ratings for an Entity There can be more than one Rating set for an Entity per User. 用户为一个实体添加一组等级。每个用户可以为一个实体设置多个等级。
For example, let's say the Entity is a car. 例如,假设实体是一辆汽车。 The car is rated on Appearance and Performance.
该汽车在外观和性能上得到了评价。 And a User can rate the given car's appearance and performance more than once.
用户可以多次评估给定汽车的外观和性能。 So my table looks something like this (the Rating field is not an Identity column; it is an int on a scale of 1 - 10):
所以我的表看起来像这样(Rating字段不是Identity列;它是1到10的整数):
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
Now, I have a helper method where I supply the UserID and the EntityID and I want to return the most recent set of Ratings (into a ViewModel that includes the Rating Category). 现在,我有一个辅助方法,其中提供了UserID和EntityID,并且我想返回最新的Ratings集(到包含Ratinging Category的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;
}
What kind of "where" or "group by" or "order by" do I need to add to ONLY grab the most recent set of Ratings for the given UserID and EntityID? 我需要添加哪种“位置”或“分组依据”或“排序依据”,以便仅获取给定UserID和EntityID的最新等级集?
Thanks! 谢谢!
Consider ordering by the DateSubmitted
on the return of the method, and then taking the number of entries that you'd like. 考虑在方法返回时按
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);
.OrderByDescending(a => a.DateSubmitted).FirstOrDefault()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.