0

I think my problem is possibly as a result of a misuse/misunderstanding of the Find() function, so this is probably not an exact duplicate issue of the null reference general thread.

I am trying to raise an alert for every single student upon the condition of their checkTime variable. I get a null reference within the for loop.

    ClientScriptManager cs = Page.ClientScript;
    Student[] myArr = new Student[db.Students.Count()];//this line is fine
    Student set = new Student();
    string[] myStringVariable = new string[db.Students.Count()];
    for (int i=0;i<db.Students.Count();i++)
    {
        set = db.Students.Find(i);
        myStringVariable[i] = "times up: " + set.checkTime; //System.NullReferenceException: 'Object reference not set to an instance of an object.'

        myArr[i]= db.Students.Find(i);
       // if (DateTime.Now >= myArr[i].checkTime)//err:object reference not set to instance of an Object
        //{


        //}
        ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + myStringVariable[i] + "');", true);
    }

here is my model code : extra details : It's some example code gotten from the web and the general Idea is to try and convert it into a project managing program, whereby I can add and remove objects from the dbSet, and specify an expiry time for those objects.

This is my attempt at accessing the checkTime value of every single object by iterating through it all and then attempting to throw up an allert for every one that has met the expiry condition.

   using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.ComponentModel.DataAnnotations;
using System.Collections;

namespace ContosoUniversityModelBinding.Models
{
    public class SchoolContext : DbContext
    {
        public DbSet<Student> Students { get; set; }
        public DbSet<Enrollment> Enrollments { get; set; }
        public DbSet<Course> Courses { get; set; }

    }

    public class Student
    {
        [Key, Display(Name = "ID")]
        [ScaffoldColumn(false)]
        public int StudentID { get; set; }

        [Required, StringLength(40), Display(Name = "Last Name")]
        public string LastName { get; set; }

        [Required, StringLength(20), Display(Name = "First Name")]
        public string FirstName { get; set; }

        [EnumDataType(typeof(AcademicYear)), Display(Name = "Academic AcademicYear")]
        public AcademicYear Year { get; set; }

        [Range(typeof(DateTime), "1/1/2013", "1/1/3000", ErrorMessage = "Please provide an enrollment date after 1/1/2013")]
        [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:d}")]
        public DateTime EnrollmentDate { get; set; }

        [Range(typeof(DateTime), "1/1/1900", "1/1/3000", ErrorMessage = "Please provide a Deadline for this project!")]
        [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:d}")]
        public DateTime checkTime { get; set; }//each added student has a timer


        public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
        {
            if (DateTime.Now >= checkTime)
            {
                yield return
                  new ValidationResult(errorMessage: "Project Deadline Reached/Surpassed",
                                       memberNames: new[] { "checkTime" });
            }
        }

        public virtual ICollection<Enrollment> Enrollments { get; set; }
    }


    public class Enrollment
    {
        [Key]
        public int EnrollmentID { get; set; }
        public int CourseID { get; set; }
        public int StudentID { get; set; }
        public decimal? Grade { get; set; }
        public virtual Course Course { get; set; }
        public virtual Student Student { get; set; }
    }

    public class Course
    {
        [Key]
        public int CourseID { get; set; }
        public string Title { get; set; }
        public int Credits { get; set; }
        public virtual ICollection<Enrollment> Enrollments { get; set; }
    }
    public enum AcademicYear
    {
        Freshman,
        Sophomore,
        Junior,
        Senior
    }
}
timi95
  • 368
  • 6
  • 23
  • See the duplicate, set breakpoints, step through your code and inspect your variables. What's the problem here is that if `set` is `null` after `set = db.Students.Find(i)`, then no student with a PK with the value of `i` exists. – CodeCaster Jun 23 '17 at 14:09
  • Do not use DbModel as ViewModel, your teacher should deduct points for that. – PTwr Jun 23 '17 at 14:11
  • It's likely that `Find` uses a column, and not the array index, so `i` could represent a column value that is not in base. – Kilazur Jun 23 '17 at 14:12
  • @Kilazur so what function other than Find() might I use to get Students from the database ? – timi95 Jun 23 '17 at 14:41
  • If db.Student is an array, you can use `db.Students[i]`, if it's an IEnumerable, use `db.Students.ElementAt(i)` (or `db.Students.At(i)`, I'm not sure) – Kilazur Jun 23 '17 at 14:43
  • @Kilazur Students is actually DbSet ; Is a DbSet not accessible in any of the ways I've tried ? I'm getting an error called : "System.NotSupportedException: 'LINQ to Entities does not recognize the method " – timi95 Jun 23 '17 at 15:08
  • Oh, then either work on db.Students.ToList() if you're gonna fetch all the students anyway, or use db.Students.Skip(I).First() if not – Kilazur Jun 23 '17 at 15:32

0 Answers0