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; }
}
}
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
});
}
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With