public string Studentbyteacher(long _id)
{
using (var context = new DbContext())
{
var studentID = (context.TeacherStudent.Where(x => x.TeacherID == _id).Select(x => x.studentID));
foreach (var id in studentID)
{
var strJSON = JsonConvert.SerializeObject(context.Student.Where(x => x.ID == id).ToList());
return strJSON;
}
return null;
}
}
注意:我在数组列表中获得学生ID,如[0] 1,[1] 2,[2] 3 ......等等。所以我想根据ID返回学生的详细信息。如果我错了,请纠正我。
答案 0 :(得分:0)
我认为您正在寻找可用于在循环中返回IEnumerable< T >
或IEnumerable
的收益率回报。
首先,您需要将方法更改为:
public IEnumerable<string> Studentbyteacher(long _id)
并更改行
var strJSON = JsonConvert.SerializeObject(context.Student.Where(x => x.ID == id).ToList());
到
yield return JsonConvert.SerializeObject(context.Student.Where(x => x.ID == id).FirstOrDefault());
最后删除return strJson;
答案 1 :(得分:0)
public string Studentbyteacher(long teacherId)
{
using (var context = new DbContext())
{
var students =
from teacherStudent in context.TeacherStudent.Where(x => x.TeacherID == teacherId)
let studentId = teacherStudent.studentID
let student = context.Student.Where(x => x.ID == studentId).Single()
select student;
return JsonConvert.SerializeObject(students);
}
}