Lambda Select Top 1 item on underlying List

c# entity-framework-6 lambda linq

Question

I have two related tables.

Customer

Id, Nbr, Name

Assignments

Id, CustomerId, Location, AssigmentTime

Customer is related in some way. Id = Assignments CustomerId

Each customer may have a large number of assignments, but I'm only interested in the most recent one, as shown by the DateTime column. AssigmentTime

A query like this should be used in SQL:

Select Top 1 From Customer c
Inner Join Assigments a On c.Id = a.CustomerId
Where c.Nbr = 1234
Order By AssigmentTime Desc

I'm having trouble creating a suitable Lambda query.

Although this code works, it is not particularly efficient:

var customerNbr = 1234:
var cst = context.Customers.FirstOrDefault(x => x.Nbr == customerNbr);
if (cst != null && cst. Assigments.Count > 1)
{
  cst. Assigments = new List<Assigments>
  {
     cst.Assigments.OrderByDescending(x => x.AssigmentTime).FirstOrDefault()
  };
}

How do I get a customer when Customer.Assignments List only has one top assignment?

1
0
11/2/2017 5:13:54 PM

Popular Answer

ZZZ_tmp
1
11/2/2017 8:46:47 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow