[英]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 查询数据库上下文,但出现此错误:
LINQ to Entities does not recognize the method 'Int32 Int32(System.String)' method, and this method cannot be translated into a store expression.` LINQ to Entities 无法识别方法 'Int32 Int32(System.String)' 方法,并且此方法无法转换为存储表达式。`
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" “当前上下文中不存在名称‘o’”
This is my code for the class GetCourseName
这是我的GetCourseName
类的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 (ie (int) o.CourseId).如果您不想具体化查询(检索数据),您可以使用强制转换(即 (int) o.CourseId)。 Is converted to SQL CAST AS statement.转换为 SQL CAST AS 语句。
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. 'o' 脱离上下文的错误是您仅在 Linq 查询中声明 o 并且只能在该范围内引用它。
Explicit conversion is simple and works: (int)o.CourseID显式转换既简单又有效:(int)o.CourseID
var course = from o in entities.UniversityCourses
select new CourseNames
{
CourseID = (int)o.CourseID,
CourseName = o.CourseName,
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.