Home > Blockchain >  function Return LastOrDefault()
function Return LastOrDefault()

Time:12-24

I have ExpesnseIDVM ViewModel that only contains 1 variable ExpenseID to hold the last value from the database

public IEnumerable<ExpesnseIDVM> Profile(LoginVM loginVM)
{
    var data = (from a in context.Employees
                where a.Email == loginVM.Email
                join b in context.Expenses on a.EmployeeId equals b.EmployeeId
                select new ExpesnseIDVM()
                { ExpenseID = b.ExpenseId }).ToList().LastOrDefault();

    return data;
}

I have a problem with the return type, what type of return type should I use to get the value

CodePudding user response:

You have IQueryable?<T> as return value of the linq query, then you have .ToList() That makes EF to calculate the query, getting List<T> and finally .LastOrDefault() that returns single object of T.

CodePudding user response:

Four problems here:

  • SQL Server do not guarantee order of the items if you do not specify OrderBy
  • SQL do not have LastOrDefault direct translation. EF may try to reverse defined OrderBy and call FirstOrDefault - again OrderBy required
  • LastOrDefault returns one instance, not enumerable
  • ToList() loads whole table into the memory, but you need just one record, so do not use it.

Consider to rewrite your query in the following way:

public ExpesnseIDVM Profile(LoginVM loginVM)
{
    var data = (from a in context.Employees
                where a.Email == loginVM.Email
                join b in context.Expenses on a.EmployeeId equals b.EmployeeId
                orderby b.ExpenseId descending
                select new ExpesnseIDVM()
                { ExpenseID = b.ExpenseId }).FirstOrDefault();

    return data;
}

CodePudding user response:

LastOrDefault() will return one ExpesnseIDVM element or null if none is found yet you are returning a collection of elements, you should return one element only:

 public ExpesnseIDVM Profile(LoginVM loginVM) { ... }

I believe you may have a typo in ExpesnseIDVM, shouldn't it be ExpenseIDVM?

In Visual Studio, a quick trick to find the return type of an expression is to hover your mouse cursor over the name of the assigned variable, e.g.:

enter image description here

  • Related