-1

DateTime.ToString("MM/dd/yyyy") inside linq is throwing an error. Here is my code:

public IEnumerable<EmployeeViewModel> GetAllEmployees()
{
    List<EmployeeViewModel> vm = (
        from a in db.Employees
        select new EmployeeViewModel
        {
            EmployeeId = a.EmployeeId,
            EmployeeName = a.EmployeeName,
            HiredDateString = a.HiredDateTime.ToString("MM/dd/yyyy"),
            HiredTimeString = a.HiredDateTime.ToString("h:mm tt"),
            Description= a.Description
            }).ToList();
    return vm;
}

EDIT: HiredDateString and HiredTimeString are strings inside the ViewModel.

For which I got following error:

<Error>
<Message>An error has occurred.</Message>
<ExceptionMessage>
LINQ to Entities does not recognize the method 'System.String ToString(System.String)' method, and this method cannot be translated into a store expression.
</ExceptionMessage>
<ExceptionType>System.NotSupportedException</ExceptionType>

If I simply use: a.HiredDateTime.ToString() it won't throw an error. But it gives me full DateTime string; I want to get date and time strings separately. Thank you so much for the help.

1 Answers1

4

You can't datetime format in linq expression.You should take this:

HiredDateString = a.HiredDateTime,

and you should format this data when show.

For example in razor page:

foreach (var item in vm )
            {
                @item.HiredDateString.ToString("MM/dd/yyyy")
            }
hakantopuz
  • 481
  • 5
  • 11
  • I found the solution: I just missed .ToList() or .AsEnumerable() As I did db.Employees.AsEnumerable() , it worked as expected. – Bigyan Chapagain Jun 09 '18 at 10:48
  • 1
    Some rando just marked my question duplicate. But by no means its a duplicate one. Also down-voted it. These so called 'experts' never let new-comer to do something good. Clearly, deep down, they want to stifle new comers. – Bigyan Chapagain Jun 11 '18 at 04:43