C# LINQ to Entities 无法识别方法 'Int32 Int32(System.String)' 方法,并且此方法无法转换为存储表达式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13887296/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
LINQ to Entities does not recognize the method 'Int32 Int32(System.String)' method, and this method cannot be translated into a store expression
提问by user1905332
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
namespace IronwoodWeb
{
public class CourseNames
{
public int CourseID { get; set; }
public string CourseName { get; set; }
}
}
采纳答案by Sergey Berezovskiy
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
});
}
回答by Matthew
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 并且只能在该范围内引用它。
回答by bubi
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.
如果您不想具体化查询(检索数据),您可以使用强制转换(即 (int) o.CourseId)。转换为 SQL CAST AS 语句。
回答by user3131922
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,
};

