Search code examples
asp.net-corexmlhttprequestrelational-databaseswagger-ui

Swagger UI Post and Put problem in relational database


I am new at .NET Core. I am trying to develop sample API project but i realized a problem on the last project.Firstly i want to show my entities;

public class Student
{
    public int ID { get; set; }
    public string LastName { get; set; }
    public string FirstMidName { get; set; }
    public DateTime EnrollmentDate { get; set; }
    public ICollection<Enrollment> Enrollments { get; set; }
}


public class Enrollment
{
    public int EnrollmentID { get; set; }
    public int CourseID { get; set; }
    public int StudentID { get; set; }
    public Student Student { get; set; }
}

As you can see i am using two tables and there is a relation between 2 tables. HttpGet and HttpDelete methods are Ok. The problem is; when i tried to post a new record,swagger wants me to sent these datas:

image1

and whatever i do, i get this mistake: Swagger Fault image

Why i get this fault and why swagger wants me to send relational table datas?

Thanks for answer


Solution

  • I found the answer. When i try to use entities layer directly to match tables in SQL, i get this mistake. The problem is; API don't need ICollection properties that using for database diagrams, I mean, use entity layer directly isn't enough. I realized that have to use Dto Objects. I want to show model that required:

     public class Student
    {
        public int ID { get; set; }
        public string LastName { get; set; }
        public string FirstMidName { get; set; }
        public DateTime EnrollmentDate { get; set; }
        public ICollection<Enrollment> Enrollments { get; set; }
    }
    
     public class Enrollment
        {
            public int EnrollmentID { get; set; }
            public int CourseID { get; set; }
            public int StudentID { get; set; }
            public Student Student { get; set; }
        }
    
    
        public class StudentDto
    {
        public int ID { get; set; }
        public string LastName { get; set; }
        public string FirstMidName { get; set; }
        public DateTime EnrollmentDate { get; set; }
    }
    
    public class EnrollmentDto
    {
        public int EnrollmentID { get; set; }
        public int CourseID { get; set; }
        public int StudentID { get; set; }
    }
    

    So, i used Dto objects to match API with Database