Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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; }
    }
}
like image 681
user1905332 Avatar asked Dec 14 '12 22:12

user1905332


3 Answers

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
                  });
}
like image 147
Sergey Berezovskiy Avatar answered Oct 05 '22 08:10

Sergey Berezovskiy


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.

like image 31
bubi Avatar answered Oct 05 '22 10:10

bubi


You could also bring back the value as a string (as it is apparently stored) and then Convert it after.

The error on 'o' being out of the context is that you are only declaring o in the Linq query and it can only be referenced in that scope.

like image 37
Matthew Avatar answered Oct 05 '22 09:10

Matthew