This part of the code will give you this problem
if (john.courses == null)
{
john.courses.Add(stoptalk);
john.courses.Add(rails);
db.Persons.Add(john);
db.SaveChanges();
}
because if
john.courses == null
is true, the
Add
operation cannot be executed as no instance of
john.courses
has been created.
What you need to do is to initialize the member
courses
properly.
Example:
public class person
{
public int PersonId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public virtual ICollection<Course> courses { get; set;}
public person()
{
PersonId = 0;
FirstName = "";
LastName = "";
courses = new List<Course>;
}
}
</course>
Then change the if-statement:
if (john.courses.Count == 0)
{
...
}