user1531040
user1531040

Reputation: 2291

How can I select one record (ordered by descending)?

I use LINQ-TO-SQL. And I have a control Order. And in the control I have a property OrderDetail. I only want to show the last updated data. So I have to order by ChangedAt. That's a DateTime field.

When I try to open this entity. I get an error like Specified cast is not valid, while I see by debugging the selection has 1 row.

How can I select one record, ordered by descending (ChangedAt)?

The relationship between both entities Order : OrderDetail <=> 1 : n.

partial class Order : ILock, ICloneable
{
   ...
    public OrderDetail Detail
    {
        get
        {
            var detail = this.OrderDetails.Select(od => od);

            if (detail != null && detail.Count() > 0)
                return detail.OrderByDescending(od => od.ChangedAt).FirstOrDefault();
            else
                return null;
        }
    }

I don't think it's important. But I use SQL-Server as database.

Upvotes: 2

Views: 2430

Answers (1)

Michael Coxon
Michael Coxon

Reputation: 5510

You can simply do this to get the first record in the list, in descending order by ChangedAt:

public OrderDetail Detail
{
    get
    {
        return this.OrderDetails
            .OrderByDescending(od => od.ChangedAt)
            .FirstOrDefault();
    }
}

Null checking in LINQ to entities/SQL is not required as the internal expression parser handles this for you.

Upvotes: 2

Related Questions