我正在尝试使用Linq to Entities查询数据库上下文,我收到此错误:
LINQ to Entities无法识别方法'Int32 Int32(System.String)'方法,并且此方法无法转换为商店表达式。
代码:
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();
}
在看到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();
}
但它引发了一个错误:
“当前上下文中不存在名称'o'”
这是我的课程GetCourseName
namespace IronwoodWeb
{
public class CourseNames
{
public int CourseID { get; set; }
public string CourseName { get; set; }
}
}
答案 0 :(得分:37)
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
});
}
答案 1 :(得分:3)
你也可以把这个值带回一个字符串(因为它显然是存储的)然后转换它。
'o'出错的错误是你只在Linq查询中声明o并且只能在该范围内引用。
答案 2 :(得分:3)
如果您不想实现查询(检索数据),可以使用强制转换(即(int)o.CourseId)。转换为SQL CAST AS语句。
答案 3 :(得分:-1)
显式转换很简单,有效:(int)o.CourseID
var course = from o in entities.UniversityCourses
select new CourseNames
{
CourseID = (int)o.CourseID,
CourseName = o.CourseName,
};