Dave Bell

Dave Bell

  • NA
  • 108
  • 8.5k

Insert Data in table with foreign key

Feb 20 2023 9:38 PM

Hello,

I have defined 2 classes:

public class Student 
{
    public int Id { get; set; }
    public string Student_FName { get; set; }
}

public class Program
{
    public int Id { get; set; }
    public string ProgramName { get; set; }
    public int StudentId { get; set; }
    public Student Student { get; set; }
}

This created the tables accurately, with StudentId as FK in Program table. Now I am trying to insert data using below Json and getting error. How to solve it? I just wish to enter Maths as program for Student with Id = 1

In Controller, I am using

_context.Programs.Add(request.program);  
_context.SaveChanges();
{
    "programName": "Math",
    "studentId":1
}
{
    "errors": {
        "Student": [
            "The Student field is required."
        ]
    },
    "title": "One or more validation errors occurred.",
    "status": 400,
    "traceId": "00-7d3f8f9048ccf69b10f647fc7781f4a7-fa99172258bd6e1a-00"
}

Answers (4)