Conor8630
Conor8630

Reputation: 345

ASP.NET MVC Return the latest entry in table for the logged in user

I am trying to get the latest record for the logged in employee in my HolidayRequestForm table.

However based on advice from LINQ To Entities does not recognize the method Last. Really? I want to orderbydescending and select the first.

I've tried adding in orderbydescending but I get an error "Error 3 'System.Data.TypedTableBaseExtensions.OrderByDescending(System.Data.TypedTableBase, System.Func, System.Collections.Generic.IComparer)' is a 'method', which is not valid in the given context
"

Do I have it in the wrong place?

var SD = (from c in db.HolidayRequestForms.OrderByDescending
                        where (c.Employee.Email == name) && (c.Employee.EmployeeID == c.EmployeeID)
                        select c.StartDate);

        DateTime StartDate = SD.LastOrDefault();

I would like StartDate to give the latest result in the HolidayRequestForm table for the current logged in employee

Upvotes: 0

Views: 151

Answers (1)

mjwills
mjwills

Reputation: 23898

db.HolidayRequestForms.OrderByDescending

doesn't make sense for two reasons.

  1. It is a method, which needs to be invoked (i.e. have () after it)
  2. You need to tell it what to order by

I'd suggest this as a replacement:

var SD = (from c in db.HolidayRequestForms where (c.Employee.Email == name) && (c.Employee.EmployeeID == c.EmployeeID)
                        select c.StartDate).OrderByDescending(z => z);

or:

var SD = db.HolidayRequestForms
    .Where(c => c.Employee.Email == name && c.Employee.EmployeeID == c.EmployeeID)
    .OrderByDescending(z => z.StartDate)
    .Select(y => y.StartDate);

You will also want to use FirstOrDefault rather than LastOrDefault.

Upvotes: 3

Related Questions