How succesfully set a Database Relationship in .net?
Hello guys!
How is it going? I'm developing a simple App for a College's programming subject. And I'm trying to establish a correct database Relationship, but When I tried to make a GET request, Swagger throws:
The [ForeignKey] attribute for the navigation 'Students' cannot be specified on the entity type 'Subject' since it represents a one-to-many relationship. Move the [ForeignKey] attribute to a property on 'Student'.
This is the models data with their default relationship:
I tried to set a one-to-Many relationship with Teacher-Subject because a teacher can teach many subjects, while a Subject merely have a single teacher. I set the Teacher's dni as foreign and primary key, as you can see below
In the second relationship, I settled Many-Many relationship to Student-Subject, because a Student can be in many subjects and Subject containe many students. I set the Student's dni as a primary and foreign key. And I settled the Subject's Id as a primary key.
However, when I tested in Swagger, it return me the following error:
If anyone could help me, I'd be really grateful.7 Replies
think about it - if you have a one-to-many relationship to another entity, can you represent that with the key of only one of those entities?
I tried what the error told me to do it. I set the foreign outside the Subject model. Still throwing the same error, but with diferent parameters.
the problem is in your Teacher model
you try to define a one-to-many relationship to subjects but then you also define a foreign key for a subject, which doesn't make sense for that kind of relationship
in a one-to-many the "one" side doesn't have any keys to the "many," it's the other way around
So, the solution is set the foreign key in the teacher model?
no, the solution is remove it
if a teacher has a foreign key to a single subject, how does that model a relationship to many subjects?
I remove it with TeacherDni?
the error is telling you where the problem is
if you have a one-to-many relationship, the foreign key needs to be defined as part of the "many" entity to the "one" entity, not the "one" entity to a single "many" entity
do you understand why it needs to be that way?