Carlos Miguel Colanta
Carlos Miguel Colanta

Reputation: 2823

Count() keeps on giving me 0 even though there is a row returned

Okay so, i have an enrollment website and part of it prevents the user from re-enrolling the class.

My code goes like this(originally):

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
}
}

Last night, it was working fine but when i tested it again it doesn't anymore.

Normally, it's just simple, what i need to do is just count the rows returned, if it's 0 then there are no duplicates. I can do that by using Count() but it doesn't work anymore.

I decided to check the values per breakpoint.

Results:

First value is enter image description here

while the second is

enter image description here

I decided to rerun the query to check: enter image description here

so there should be a row but the Count() keeps on giving me 0 thus allowing the user to re-enroll the subject(which they shouldn't be)

My program will work if i change it to if(query == null) but i wanna know why does it keep on giving me 0? I swear it was working fine last night.

enter image description here

Upvotes: 0

Views: 134

Answers (1)

user3559349
user3559349

Reputation:

Your query is incorrect

 where subj.studid == st.id && subj.studid == sbj.id // both refer to studid

should be

 where subj.studid == st.id && subj.subjid== sbj.id

Strongly recommend you follow normal naming conventions to minimise the risk of error like this (i.e. your fields should be named StudentId and SubjectId)

Upvotes: 6

Related Questions