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"
}
Naimish MakwanaPosted Feb 21, 2023, 3:41 AM
Hello Bell,
you need to create a new
Programobject and set itsProgramName,StudentId, andStudentproperties using the corresponding values from the JSONThis is because the
Studentproperty in theProgramclass is defined as a navigation property, which means it is used to establish a relationship between theProgramandStudententities.You can try below solution.
Thanks
Naimish Makwana
Tuhin PaulPosted Mar 15, 2023, 1:22 AM
The error message indicates that the Student field is required, which means that you need to include a Student object in the Program object that you are adding. You can modify your code to create a Student object and set its Id property to the studentId value from the JSON. Then, you can assign the Student object to the Student property of the Program object before adding it to the database. Here's an example:
This code first tries to find the Student object with the specified Id. If it exists, it uses that object. If it doesn't exist, it creates a new Student object with the specified Id. Then, it creates a new Program object and assigns the Student object to its Student property. Finally, it adds the Program object to the context and saves changes to the database.
Dave BellPosted Feb 21, 2023, 3:37 AM
Sorry...that did not work. If you see Student is not a list but an object used to establist foreign key with Program.
But that gave me idea and below worked..made Student? nullable...
Vishal JoshiPosted Feb 21, 2023, 3:01 AM
Hello Bell,
You need to pass all fields as mentioned in the class. or you need to set nullable in entity/database. you can try the below JSON to get it to work.
Thanks