0

I have this sql query which works fine

    select u.FirstName,u.LastName,case when ei.Gender=1 then 'Male' else 'Female' end as Gender,t.Name as 'Team Name',ei.MobileNumber,u.Phone as 'Alternative Number',u.EmailAddress,ei.AlternateEmailAddress,ei.GMail,ei.Skype,FORMAT(ei.DateOfBirth,'dd-MMM-yyyy') AS BirthDay,ei.Address1,ei.Address2,ei.City,ei.[State],ei.Country,ei.ZipPostalCode,ei.Designation,ei.MasterLeaves
 from Employee e
inner join [user] u
on e.[User]=u.Id and IsDeleted!=1
inner join Team t 
on e.Team=t.Id
inner join EmployeeInformation ei
on e.AdditionalInformation=ei.Id

when I converted the same query to linqued query i.e

    var EmpReport = (from Emp in db.Employees
                 join Usr in db.Users
                 on Emp.User equals Usr.Id
                 join Tm in db.Teams
                on Emp.Team equals Tm.Id
                 join Ei in db.EmployeeInformations
                 on Emp.AdditionalInformation equals Ei.Id
                 where Usr.IsDeleted  != true
                select new { Usr.FirstName, Usr.LastName, Gender = Ei.Gender == 1 ? "Male" : "Female", Team_Name = Tm.Name, Ei.MobileNumber, Alternative_Number = Usr.Phone, Email_Address = Usr.EmailAddress, Alternate_Email_Address = Ei.AlternateEmailAddress, Ei.GMail, Ei.Skype, Birthday = Ei.DateOfBirth.ToString("dd-MMM-yyyy"), Ei.Address1, Ei.Address2, Ei.State, Ei.Country, Ei.ZipPostalCode, Ei.Designation, Ei.MasterLeaves }).ToList();

it gave me this error

 LINQ to Entities does not recognize the method 
     'System.String ToString(System.String)' method, and this method cannot
      be translated into a store expression.

The Error is basically causing in this part

Birthday = Ei.DateOfBirth.ToString("dd-MMM-yyyy").

where I have gone wrong?

akash
  • 173
  • 1
  • 14

1 Answers1

3

You're getting the error because DateTime.ToString() is a .NET function and not directly translateable to SQL. Either return your DateOfBirth column in its native format and change the format once you have your results in your app, or use some of the SQL functions available in Linq-to-Entities, see this answer: https://stackoverflow.com/a/16364484/5785878

Community
  • 1
  • 1
James
  • 1,028
  • 9
  • 20