Error: Object reference not set to an instance of an object

2

I'm having the following error:

  

Object reference not set to an instance of an object

Can anyone identify the 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;
    }
}
    
asked by anonymous 08.09.2015 / 22:54

1 answer

4

You failed to initialize the virtual list in the class constructor and set the type of the list.

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;
    }
}
    
19.05.2016 / 22:52