alexcryout
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(Http StatusCode .NotFound) ;
else
return result.Cast<string>().ToLi st();
}
}
}
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!
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(Http
else
return result.Cast<string>().ToLi
}
}
}
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!
Add a WHERE clause to your LINQ query and exclude the NULL Departments and try.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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();
}
}