Model relationships causes trouble with Swagger/endpoints

Viewed 482

I have two entities, Classroom, and Student. One-to-many relationships and I use EF Core: one Classroom can have many Students, and one Student can be in one Classroom.

public class Classroom
{
    public int ClassroomId { get; set; }
    public List<Student> Students{ get; set; }
}

public class Student
{
    public int StudentId { get; set; }
    public string Name { get; set;
    public int ClassroomId { get; set; }
    public Classroom Classroom { get; set; }
}

To make this as short as possible I have left out Controller, DataContext, DbSet<> for tables, etc., but I have created it all.

Now, if I run my application and I want to POST a Classroom through Swagger, it includes the list of students in the model schema, so that I have to create the list of students as if it was a property that I wanted to create at the same time as I create a classroom. Similarly, if I want to create/POST a student, it includes the classroom in the model schema.

Instead, I want to be able to create a Classroom and Student separately. When I create a Student, I want to be able to specify only the Classroom Id, so that I can connect students to existing classrooms, not create them same time.

How do I go about this? I am sure I misunderstand something, so I appreciate all help I can get. Thanks

1 Answers

How do I go about this?

You do not expose your database models to the outside world. They are your database models, not your data exchange objects. Nobody but your ORM needs to see them or should see them, you can annotate them so your database layer will know what to do.

Your controller layer should have a set of model classes that you use to talk to the outside world via REST (using swagger). You can build them however you see fit, you can annotate them so your REST layer will understand what to do.

Then you need to map the models you get from the outside world to something you want to do with your database. That should be quite straightforward.

Related