如何按嵌套实体的字段排序/排序

本文关键字:排序 字段 实体 何按 嵌套 | 更新日期: 2023-09-27 18:06:03

这是怎么做到的?

context.Subscriptions
.Include("TvShow.News")
.Include("User")
.Where(s => s.UserId == userId)
.OrderByDescending(t => t.TvShow.News.CreatedOnDatetime)
.ToList();

OrderByDescending在这种情况下不起作用,我把它放在那里只是为了更容易理解问题。

如何按嵌套实体的字段排序/排序

我终于用这段面条式代码让它工作了:

// NASTY NASTY ENTITY FRAMEWORK
var anonymousObjects = context.Subscriptions
    .Where(c => c.UserId == userId)
    .Select(s => new
    {
        SubscriptionId = s.Id,
        TvShowId = s.TvShowId,
        TvShow = s.TvShow,
        TvShowNews = s.TvShow.News.OrderByDescending(n => n.CreatedOnDatetime),
        UserId = s.UserId,
        User = s.User
    });
anonymousObjects = anonymousObjects.OrderByDescending(x => x.TvShowNews.Max(n => n.CreatedOnDatetime));
var subscriptions = new List<Subscription>();
foreach (var oneAnonymousObject in anonymousObjects)
{
    var subscription = new Subscription
    {
        Id = oneAnonymousObject.SubscriptionId,
        TvShowId = oneAnonymousObject.TvShowId,
        UserId = oneAnonymousObject.UserId,
        TvShow = new TvShow
        {
            Id = oneAnonymousObject.TvShow.Id,
            Title = oneAnonymousObject.TvShow.Title,
            CreatedOnDatetime = oneAnonymousObject.TvShow.CreatedOnDatetime,
            IsPrivate = oneAnonymousObject.TvShow.IsPrivate,
            TotalSubscriptions = oneAnonymousObject.TvShow.TotalSubscriptions,
            News = oneAnonymousObject.TvShowNews.ToList()
        },
        User = oneAnonymousObject.User
    };
    subscriptions.Add(subscription);
}

实体框架团队,如果你看到这个,请,请,请让它更容易。