none
Cant find the error: System.NullReferenceException RRS feed

  • Question

  • Cant find the error:

    An unhandled exception of type 'System.NullReferenceException' occurred in Project1.Console.exe

    Additional information: Object reference not set to an instance of an object.

    -------------------------------------

    class Program
        {
            static void Main(string[] args)
            {
                using (var db = new MyContext())
                {
                    var student = new Student() {Name = "MyName"};
                    var mathSubject = new Subject() {Name = "Math"};
                    var portSubject = new Subject() {Name = "Portuguese"};

                    student.Subjects.Add(mathSubject);
                    student.Subjects.Add(portSubject);

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

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

        public class Subject
        {
            public int SubjectId { get; set; }
            public string Name { get; set; }
            public virtual Student Student { get; set; }
        }

        class MyContext: DbContext
        {
            public DbSet<Student> Students { get; set; }
            public DbSet<Subject> Subjects { get; set; }
        }

    Wednesday, August 6, 2014 3:32 PM

Answers

All replies