Error: Object Reference not set to an instance of an Object

Asked

Viewed 686 times

2

I’m having the following mistake:

Object Reference not set to an instance of an Object

Can anyone identify which error in my code?

Follow my classes:

Program:

class Program {
    static void Main(string[] args) {
        using(var db = new StudentContext()) {

            var student = new Student() {
                Name = "Kelly Soares"
            };
            var mathSubj = new Subject() {
                Name = "Mathematics"
            };
            var scienceSubj = new Subject() {
                Name = "Data Structures"
            };

            student.Subjects.Add(mathSubj);
            student.Subjects.Add(scienceSubj);

            db.Students.Add(student);
            db.SaveChanges();
        }
    }
}

Student:

public class Student {
    public int StudentId {
        get;
        set;
    }
    public string Name {
        get;
        set;
    }
    public virtual List Subjects {
        get;
        set;
    }
}

Subject:

public class Subject {

    public int SubjectId {
        get;
        set;
    }

    public string Name {
        get;
        set;
    }

    public virtual Student Students {
        get;
        set;
    }
}

StudentContext:

public class StudentContext: DbContext {
    public StudentContext(): base(@"Data Source=(local); Initial Catalog=tempdb; Integrated Security=true")     {

    }
    public DbSet < Student > Students {
        get;
        set;
    }
    public DbSet < Subject > Subjects {
        get;
        set;
    }
}
  • On which line the error occurs?

  • It is very likely that you are not using version 6 of efand the Lists are not being initialized alone...

  • 1

    Bruno, he’s already making an error on this student.Thesubjects Add(mathSubj) line; so he tries to make the first insertion.

  • You can also put the Stack Trace in your question, please?

1 answer

4


You haven’t initialized the virtual list in the class constructor and set the list type.

public class Student
{

    public Student()
    {
        Subjects = new List<Subject>();
    }

    public int StudentId
    {
        get;
        set;
    }
    public string Name
    {
        get;
        set;
    }

    public virtual List<Subject> Subjects
    {
        get;
        set;
    }
}
  • 1

    Ismael worked. Grata!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.