根据正在解析的id列表查询数据

时间:2014-09-25 21:31:45

标签: c# linq entity-framework oracle11g

所以我得到了一个正在解析我的构造函数的ID列表。工作是获取与列表中的ID匹配的记录。到目前为止,我已经尝试过:

 void displayChosenIDs(List<int> ids)
        {
            bool flag = false;


            List<Student> student_record = new List<Student>();

            //Display the interests IDs on grid
            using(StudentEntities context = new StudentEntities())
            {
                //get students correspond to ones in the list
                foreach(int value in ids)
                {
                    Student rec =  (Student)(from o in context.Students
                                    where o.ID.CompareTo(value) == 0
                                    select o);
                    student_record.Add(rec);
                }
}

我收到错误消息,指出无法使用我的linq键入强制转换并输入强制转换为学生。有没有其他方法可以使用linq而不需要foreach()?

1 个答案:

答案 0 :(得分:1)

您收到InvalidCastException因为select会返回IQueryable<Student>,而不是Student。您可以使用WhereContains

在一行中实现您想要的效果
student_record.AddRange(context.Students.Where(x => ids.Contains(x.ID)));

// Or:
var student_record = context.Students.Where(x => ids.Contains(x.ID)).ToList();