Link to home
Start Free TrialLog in
Avatar of alexcryout
alexcryoutFlag for United States of America

asked on

Unable to cast the type 'Anonymous type' to type 'System.String'.

Hi Expert,

I have the codes has no error on compiling but get error when execute it.

public class DepartmentController : ApiController
    {
      private DeptEntities db = new DeptEntities();
      List<string> departments = new List<string>();
      
      public IEnumerable<string> GetDept()
      {
            using (DeptEntities context = new DeptEntities())
            {
                  var result = (from Department in db.Department orderby Department.ID
                                      select new
                                      {
                                            DepartmentName = Department.Name
                                      }).Distinct();

                  if (result == null)
                        throw new HttpResponseException(HttpStatusCode.NotFound);
                  else                  
                        return result.Cast<string>().ToList();

            }

      }
}

Error:
Unable to cast the type 'Anonymous type' to type 'System.String'.
LINQ to Entities only supports casting EDM primitive or enumeration types.

Please help!
Avatar of Akilandeshwari N
Akilandeshwari N

Add a WHERE clause to your LINQ query and exclude the NULL Departments and try.
ASKER CERTIFIED SOLUTION
Avatar of louisfr
louisfr

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of alexcryout

ASKER

Thanks louisfr. It works!
I think you can remove all the code after the query. It should never return null, it's already strings, and the return type is IEnumerable.
public IEnumerable<string> GetDept()
{
    using (DeptEntities context = new DeptEntities())
    {
        return (from Department in db.Department orderby Department.ID
                select Department.Name
               ).Distinct();
    }
}

Open in new window