我正在尝试在“用户”页面上创建一个Feed,如果用户最近喜欢某些内容,创建了一个项目,在帖子上发表了评论,那么它将会显示。我将如何操作?我正在考虑从数据库中获取不同信息的对象列表,然后按日期排序,但我无法正确订购代码。
答案 0 :(得分:1)
怎么样:
var feed = db.Likes
.Where(like => like.UserID == currentUserID)
.Where(like => like.CreatedAt > createdSince)
.OrderByDescending(like => like.CreatedAt)
.Select(like => new {
Type = "like",
CreatedAt = like.CreatedAt
})
.Concat(db.Comments
.Where(comment => comment.UserID == currentUserID)
.Where(comment => comment.CreatedAt > createdSince)
.OrderByDescending(comment => comment.CreatedAt)
.Select(comment => new {
Type = "comment",
CreatedAt = comment.CreatedAt
})
);
根据需要添加更多Concat语句,只要它们投射到相同的结构(anon或实际类),就可以将它们合并到一个列表中。
如果您不喜欢有一个巨大的陈述,并且有一个类来存储项目(例如Feed
),那么选择第一个并执行.ToList()
,那么您将拥有{{1}您可以为要包含的每个额外项目调用List<Feed>
。
只需对每个列表进行排序并提供额外的过滤器。将它们合并为一个后,您就可以对合并列表进行排序。
答案 1 :(得分:1)
好吧,我最终做的事情就是这样:
public class UserFeed
{
public string Type { get; set; }
public int Reference_Id { get; set; }
public int Comic_Id { get; set; }
public int Chapter_Id { get; set; }
public int Page_Id { get; set; }
public int User_Id { get; set; }
public string Title { get; set; }
public string Text { get; set; }
public decimal Rating { get; set; }
public string Image { get; set; }
public DateTime Date { get; set; }
}
List<UserFeed> userFeed = new List<UserFeed>();
userFeed.AddRange(user.SelectMany(i => i.UserFavorites).Select(i => new UserFeed { Type = "UserFavorite", Reference_Id = i.UserFavorite_Id, Comic_Id = i.Comic_Id, Title = i.Comic.Title, Image = i.Comic.ComicImage, Date = i.DateFavorited }).OrderByDescending(i => i.Date).Take(6));
userFeed.AddRange(Comics.SelectMany(i => i.ComicReviews).Select(i => new UserFeed { Type = "ComicReview", Reference_Id = i.ComicReview_Id, Comic_Id = i.Comic_Id, Title = i.Comic.Title, Text = i.Text, Rating = i.ComicRating.Rating, Image = i.Comic.ComicImage, Date = i.DatePublished }).OrderByDescending(i => i.Date).Take(6));
userFeed.AddRange(Comics.SelectMany(i => i.Chapters).Select(i => new UserFeed { Type = "Chapter", Reference_Id = i.Chapter_Id, Comic_Id = i.Comic_Id, Title = i.Title, Image = i.Comic.ComicImage, Date = i.DatePublished }).OrderByDescending(i => i.Date).Take(6));
userFeed.AddRange(Comics.SelectMany(i => i.Chapters.SelectMany(j => j.Pages)).Select(i => new UserFeed { Type = "Page", Reference_Id = i.Page_Id, Chapter_Id = i.Chapter_Id, Title = i.Title, Image = i.PageImage, Date = i.DatePublished }).OrderByDescending(i => i.Date).Take(6));