0

I am trying to return employee with three column in .net webapi with entity framework but return gives error saying cannot convert type pf anonymous to emp ..what I am missing

public List<EMPLOYEE_DTLS> GetLoginInfo(string UserId)
{
    var result = (from emp in db.EMPLOYEE_DTLS
                  where emp.UserId == UserId
                  select new
                  {
                      emp.FullName,
                      emp.Role,
                      emp.Designation
                   }).ToList();

    return result;
}

2 Answers2

0

Your method returns List<EMPLOYEE_DTLS>, but you are trying to return List of anonymous type.

Assuming you EMPLOYEE_DTLS class has properties FullName, Role and Designation change the type you are selecting:

public List<EMPLOYEE_DTLS> GetLoginInfo(string UserId)
{
   var result = (from emp in db.EMPLOYEE_DTLS
                 where emp.UserId == UserId
                 select new EMPLOYEE_DTLS
                 {
                    FullName = emp.FullName,
                    Role = emp.Role,
                    Designation = emp.Designation
                 }).ToList();

   return result;
}
koryakinp
  • 3,439
  • 5
  • 21
  • 49
0

You should use a DTO to return the list.

public class EmployeeDTO
{
       public string FullName {get; set;}
       public string Role {get; set;}
       public string Designation {get; set;}
}


public List<EmployeeDTO> GetLoginInfo(string UserId)
{
    var result = (from emp in db.EMPLOYEE_DTLS
                   where emp.UserId == UserId
                   select new EmployeeDTO
                   {
                      FullName = emp.FullName,
                      Role = emp.Role,
                      Designation = emp.Designation
                   }).ToList();

    return result;
 }
  • Thanks but getting error...The entity or complex type 'cannot be constructed in a LINQ to Entities query. – Vitthal Mokhare Aug 21 '18 at 16:28
  • Are you using the exactly same way? You can look the following link. https://stackoverflow.com/questions/5325797/the-entity-cannot-be-constructed-in-a-linq-to-entities-query By the way for the class properties emp.Designation should be Designation – umutcanturan Aug 21 '18 at 16:37