我是SQL Server中使用EF6的ASP.NET MVC C#的新手,我有3个表:
示例数据:
Cou_ID | Stud_ID
-------+--------
1 | 1
1 | 2
我想按学生姓名或课程名称在学生页面中进行搜索,例如,如果用户输入数学,则表示所有学生都需要数学 我写了这个代码,按名称正确搜索问题是按照课程名称显示错误,在此行的s.Stud_ID
StuList = db.Students.Where(x => x.StudentId == s.Stud_ID).ToList();
(注意:Stud_ID类型是数据库中的varchar)
Stud_Courses
不包含' Stud_ID'的定义没有扩展方法' Stud_ID'接受类型' List'的第一个参数。可以找到(你错过了使用指令或汇编引用
我的控制器代码
public JsonResult GetSearchingData(string SearchBy, string SearchValue){
List<Students> StuList = new List<Students>();
if (SearchBy == "Name")
{
StuList = db.Students.Where(x => x.StudentsName.Contains(SearchValue) || SearchValue == null).ToList();
var subCategoryToReturn = SupList.Select(S => new { supervisorName = S.supervisorName });
return Json(SupList, JsonRequestBehavior.AllowGet);
}
if (SearchBy == "Course Name")
{
var c = db.Courses.Where(x => x.CoursesName == SearchValue).SingleOrDefault();
var CN = c.CourseId;
var s = db.Stud_Courses.Where(x => x.Cou_ID == CN).ToList();
StuList = db.Students.Where(x => x.StudentId == s.Stud_ID).ToList();
// here the error happens
return Json(SupList, JsonRequestBehavior.AllowGet);}
}
Stud_Courses模型
namespace MyModel.Models{
using System;
using System.Collections.Generic;
public partial class Stud_Courses{
public int Id { get; set; }
public Nullable<int> Cou_ID { get; set; }
public string Stud_Id { get; set; }
public virtual Courses Courses{ get; set; }
public virtual Student Student { get; set; }
}}
答案 0 :(得分:0)
"s" is a List so you need to select the Stud_Id, so s will be a List. Then you can get all students that are contained in s.
var s = db.Stud_Courses.Where(x => x.Cou_ID == CN).Select(x => x.Stud_Id).ToList();
StuList = db.Students.Where(x => s.Contains(x.StudentId)).ToList();
or you can reduce the 3 separate queries to
StuList = db.Students.Where(x => x.Stud_Courses.Any(y => y.Courses.CoursesName == SearchValue)).ToList();