Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Database 如何从数据库中获取与特定记录关联的数字?_Database_Linq - Fatal编程技术网

Database 如何从数据库中获取与特定记录关联的数字?

Database 如何从数据库中获取与特定记录关联的数字?,database,linq,Database,Linq,如何从数据库中获取与特定记录关联的数字 我想要的是提取部门id的单号,我已经试过了 var course = from c in db.Courses where c.Title == courseTitle[indiciesOfSelectedCourses[sc]] select c.DepartmentID; 然后我试着这样做: int inn =Convert.ToInt32(course.FirstOrDefault()); 还尝试了其他方法,但始终存在Linq错误。如何在此调

如何从数据库中获取与特定记录关联的数字

我想要的是提取部门id的单号,我已经试过了

 var course = from c in db.Courses where c.Title == courseTitle[indiciesOfSelectedCourses[sc]] select c.DepartmentID;
然后我试着这样做:

 int inn =Convert.ToInt32(course.FirstOrDefault());

还尝试了其他方法,但始终存在Linq错误。如何在此调用中仅获取与特定课程标题关联的唯一编号?

您的查询将返回与您的条件匹配的所有课程的部门ID。您可以选择FirstOrDefault id

 var id = (from c in db.Courses 
           where c.Title == courseTitle[indiciesOfSelectedCourses[sc]] 
           select c.DepartmentID).FirstOrDefault();
或者最好选择第一个或默认课程,如果课程不为空,则获取id

 var title = courseTitle[indiciesOfSelectedCourses[sc]];
 var course = db.Courses.FirstOrDefault(c => c.Title == title);

 if (course != null)
 {
     var id = course.DepartmentID;
     // ...
 }
或者,如果可以有许多匹配的课程,则可以枚举结果:

 var ids = from c in db.Courses 
           where c.Title == courseTitle[indiciesOfSelectedCourses[sc]] 
           select c.DepartmentID;

 foreach(var id in ids)
    // ...

怎么了?这将使识别问题变得更容易。这将使
课程成为什么类型?谢谢Sergey,我使用了第二种方法,它非常有效。再次感谢!!!