I built this sample to help example my problem related to navigation properties to insert related entities. I am getting the error Error System.ArgumentNullException: 'Value cannot be null. Parameter name: source' because of student2 not having data for course.
Is there a way to insert this data and not get this error?
{
static void Main(string[] args)
{
var Course = new Course();
Course.Id = 1;
Course.studentID = 1;
Course.Name = "Math";
var student1 = new student();
student1.Id = 1;
student1.Name = "Sam";
student1.Courses.Add(Course);
var student2 = new student();
student2.Id = 2;
student2.Name = "Bill";
}
}
public class student
{
public int Id {get; set;}
public string Name { get; set; }
public List<Course> Courses { get; set; }
}
public class Course
{
public int Id { get; set; }
public int studentID { get; set; }
public string Name {get; set;}
}
}```
Saving data
```var newStudent = db.Student
.Include(x => x.Course);
var newInsertStudent = new EFModel.Student
{
Id = s.id,
Name = s.Name,
Courses = s.Courses.Select(p => new EFModel.Course
{
Id = p.Id,
studentID = s.id,
Name = s.name
}).ToList()
};
newStudent.Student.Add(newInsertStudent);```
CodePudding user response:
Try this: add a ? after s.Courses... this will make it not attempt to call into Select if Courses is null
var newInsertStudent = new EFModel.Student
{
Id = s.id,
Name = s.Name,
Courses = s.Courses?.Select(p => new EFModel.Course
{
Id = p.Id,
studentID = s.id,
Name = s.name
}).ToList()
};