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

c# entity-framework linq

Question

I am trying to Query Database Context using Linq to Entities and I am getting this error:

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

Code:

public IEnumerable<CourseNames> GetCourseName()
{
   var course = from o in entities.UniversityCourses
                select new CourseNames
                {
                    CourseID = Convert.ToInt32(o.CourseID),
                    CourseName = o.CourseName,
                 };
   return course.ToList();
}

I tried like this after seeing this

public IEnumerable<CourseNames> GetCourseName()
{
    var temp = Convert.ToInt32(o.CourseID);
    var course = from o in entities.UniversityCourses
                 select new CourseNames
                 {
                     CourseID = temp,
                     CourseName = o.CourseName,
                 };
    return course.ToList();
}

But it throws an error:

"The name 'o' does not exist in the current context"

This is my code for the class GetCourseName

namespace IronwoodWeb
{
    public class CourseNames
    {
        public int CourseID { get; set; }
        public string CourseName { get; set; }
    }
}
1
17
3/26/2019 7:38:36 AM

Accepted Answer

public IEnumerable<CourseNames> GetCourseName()
{
    var courses = from o in entities.UniversityCourses
                  select new { o.CourseID, o.CourseName };

    return courses.ToList() // now we have in-memory query
                  .Select(c => new CourseNames()
                  {
                     CourseID = Convert.ToInt32(c.CourseID), // OK
                     CourseName = c.CourseName
                  });
}
38
12/14/2012 11:03:02 PM

Popular Answer

If you dont want to materialize the query (retrieve the data) you can use cast (i.e. (int) o.CourseId). Is converted to SQL CAST AS statement.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow