EF4.1 CodeFirst: add field to join table

I use EF 4.1 RC and CodeFirst / POCO to create my code database.

Imagine that you have a many-to-many relationship, such as Teacher-Pupils (one teacher can have many students, and one student can have many teachers). Accordingly, I have two POCOs: (1) Teacher and (2) Student.

When the EF creates the appropriate tables, you will get three tables: (1) Teachers, (2) Students, and (3) an additional join table. The connection table contains exactly two fields: Teacher_ID and Student_ID.

I was wondering if I have the opportunity to add an additional field to the connection table, for example. "Class" (the class a teacher gives to a particular teacher)?

I currently have no idea how to achieve this with just two POCOs.

So, I think that all I can do is create a third POCO (for the connection table) manually, right? This will certainly work, but then I lose nice navigational properties like oneTeacher.Students.First (), etc. This is the main reason I'm still looking for another way.

+4
source share
3 answers

This is correct and applies not only to Code-first. If you have additional fields in your connection table, you will be displayed as an object. Conversely, if you want to get an additional field in your connection table, you need to create a new object and have one-to-many or one-to-many navigation properties for Teacher and Student legal entities. In any case, you lose the convenience of access to Teacher.Students and Student.Teachers and must pass through an intermediate object.

Alternatively, you could think of modeling the database structure in different ways and extracting additional information in Teacher or Student or the fourth object. But it depends entirely on your scenario.

+5
source

Yes, the connection table cannot have a payload or you need to split it into two from one to many, which will lead to the creation of a third object for storing a PC, as well as additional properties.

+1
source

This is an idea that I have not yet found to try. Perhaps you can keep your student and teacher classes as they are and add a third POCO StudentGrade with Student , Teacher and Grade properties. Then you will need to use the free API to make sure that the relationship between many of the many between Student and Teacher and the StudentGrade class StudentGrade belongs to the same table.

Hope that helps

0
source

Source: https://habr.com/ru/post/1343936/


All Articles