C
C#11mo ago
GABRIEL22

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.
No description
No description
7 Replies
Jimmacle
Jimmacle11mo ago
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?
GABRIEL22
GABRIEL22OP11mo ago
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.
Jimmacle
Jimmacle11mo ago
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
GABRIEL22
GABRIEL22OP11mo ago
So, the solution is set the foreign key in the teacher model?
Jimmacle
Jimmacle11mo ago
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?
GABRIEL22
GABRIEL22OP11mo ago
I remove it with TeacherDni?
Jimmacle
Jimmacle11mo ago
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?
Want results from more Discord servers?
Add your server