即使返回了一行,Count()也会继续给我0

Car*_*nta 0 c# asp.net-mvc

好的,我有一个注册网站,其中一部分会阻止用户重新注册课程.

我的代码是这样的(最初):

if (sbj.enroll != sbj.max)                                                                        //check if the subject is not full this time
{
var query = (from subj in emp.SelSubj where subj.studid == st.id && subj.studid == sbj.id select subj); //now check if the user already enrolled that subject code with his id
int x = query.Count();                                                                                 //convert it to number

if (x == 0)                             //subject is not duplicate
{
  sl.studid = st.id;                      //get the student's id then set it
  sl.subjid = sbj.id;                     //get the subj's id then set it
  sl.status = "P";                        //set the initial status to P
  emp.SelSubj.Add(sl);                    //add it to the database ofc
  sbj.enroll++;
  emp.SaveChanges();                      //save changes
  sb.Append(sbj.subj + " ");              //append the log
  TempData["success"] = sb.ToString();    //activate tempdata if there is atleast one subjects
}
else
{
duplicate.Append(sbj.subj + " ");                    //if the user failed the duplicate, append the subject 
TempData["duplicate"] = duplicate.ToString();       //activate tempdata if there is atleast one duplicates
}
}
Run Code Online (Sandbox Code Playgroud)

昨晚,它工作正常,但当我再次测试它不再.

通常,它只是简单,我需要做的只是计算返回的行数,如果它0是没有重复.我可以通过使用Count()它来做到这一点,但它不再起作用.

我决定检查每个断点的值.

结果:

第一个价值是 在此输入图像描述

而第二个是

在此输入图像描述

我决定重新运行查询以检查: 在此输入图像描述

所以应该有一行但是Count()继续给我0这样允许用户重新注册主题(他们不应该这样)

如果我改变它我的程序将工作,if(query == null)但我想知道为什么它继续给我0?我发誓昨晚工作正常.

在此输入图像描述

小智 6

您的查询不正确

 where subj.studid == st.id && subj.studid == sbj.id // both refer to studid
Run Code Online (Sandbox Code Playgroud)

应该

 where subj.studid == st.id && subj.subjid== sbj.id
Run Code Online (Sandbox Code Playgroud)

强烈建议您按照正常的命名约定,以尽量减少错误的这样的风险(即你的领域应该命名为StudentIdSubjectId)