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

时间:2015-08-02 17:33:56

标签: c# asp.net-mvc linq entity-framework

怎么可能这样呢?

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

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

1 个答案:

答案 0 :(得分:0)

我终于得到了这个意大利面条代码:

// 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);
}

实体框架团队,如果您看到这一点,请将此更容易。