一尘不染

LINQ to Entities无法识别方法'Int32 Int32(System.String)'方法,并且该方法无法转换为商店表达式

c#

我正在尝试使用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();
}

看到这个我就这样尝试了

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; }
    }
}

阅读 507

收藏
2020-05-19

共1个答案

一尘不染

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
                  });
}
2020-05-19