开发者

Ordering sub-collections in an EF/LINQ query

I am having trouble figuring out how (and where) to order a subcollection in a LINQ/EF query.

Basically I have a collection of SubscriptionTypes, each having its own collection of Subscriptions. I would like each Subscription in the collection to be ordered by NumberOfMonths.

Here is my current query:

    public IQueryable<SubscriptionType> SubscriptionTypesByProperty(string propertyCode)
{
    return from a in db.SubscriptionTypes.Include("Subscriptions")
           where a.Subscriptions.Any(x => x.PropertyCode == propertyCode)
           select a;
}

I would like the Subscriptions to be ordered by NumberOfMonths. I tried this:

    public IQueryable<SubscriptionType> SubscriptionTypesByProperty(string propertyCode)
    {
        return from a in db.SubscriptionTypes.Include("Subscriptions")
               where a.Subscriptions.OrderBy(q => q.NumberOfMonths).Any(x => x.PropertyCode == propertyCode)
               select a;
    }

.. but that did not order the subscriptions correctly.

Does anybody know of an easy way to do this?

UPDATE: SubscriptionType and Subscription are types generated by the 开发者_JAVA百科EF designer.

Thanks, Adam


Change your select part to sth like this

   select new SubscriptionType{ ?,?,?, 
                    Subscriptions = a.Subscription.OrderBy(b=>b.?)}


You can change your existing query to this, and it should do what you're looking for.

public IQueryable<SubscriptionType> SubscriptionTypesByProperty(string propertyCode)
{
    return from a in db.SubscriptionTypes.Include("Subscriptions")
           where a.Subscriptions.Any(x => x.PropertyCode == propertyCode)
           order by a.NumberOfMonths descending
           select a;
}

Obviously, descending could be ascending if that's what you want.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜