Inserting with Foreign Keys getting Null Value ( value not set as an object reference) using LINQ

  • Thread starter Thread starter Etolf
  • Start date Start date
E

Etolf

Guest
Here is My model Class

public class Student
{
public int Id { get; set; }
public string Student_FirstName { get; set; }
public string Student_LastName { get; set; }
public string Course { get; set; }
public List<Subject> Subjects { get; set; }
}

public class Subject
{
public int Id { get; set; }
public string SubjectName { get; set; }
public string SubjectTimeFrom { get; set; }
public string SubjectTimeTo { get; set; }
public string InstructorName { get; set; }
public int RoomNumber { get; set; }
}
and Here is My Linq that will Insert to Subject Table if Student exist

var stud = _context.Students.FirstOrDefault(x => x.Id == student.StudentId);


if(stud != null)
{
Student _student = new Student();
Model.Subject s = new Model.Subject()
{
SubjectName = student.SubjectName,
InstructorName = student.InstructorName,
RoomNumber = student.Roomno,
SubjectTimeFrom = student.SubjTimeFrom,
SubjectTimeTo = student.SubjTimeTo

};

_student.Subjects.Add(s);
_context.SaveChanges();
I got an error in _student.Subjects.Add(s); Did I missed something why I always got my Subject Null?

Continue reading...
 
Back
Top