2

I have a ResearchDatabase entity that has a many-to-many relationship with a Subject entity. i.e. a Research Database belongs in one or more Subject Categories, and a Subject Category contains one or more Research Databases.

In my ResearchDatabaseConfiguration file I have the following mapping:

HasMany(rd => rd.Subjects)
                .WithMany(s => s.ResearchDatabases)
                .Map(m =>
                    {
                        m.MapLeftKey("DatabaseId");
                        m.MapRightKey("SubjectId");
                        m.ToTable("DatabaseSubjects");
                    });

OK, no problem. Works. Creates a link table.

Now I have received a new specification. The ordering of the Research Databases in each subject is going to be split up with the most relevant first (as deemed by a user) in alphabetical order, followed by a second set of 'if you didn't find it, try these also' databases, also in alphabetical order. So, basically, I need another column to signify if the database is in the first or second group. Something like an IsPrimary column, or something like that inside the link table itself. I hope that makes sense.

But, how do I add an extra column to the link table that is created from the above mapping code?

adimauro
  • 233
  • 1
  • 12

1 Answers1

3

It's not possible. The many-to-many join table is managed internally by Entity Framework and it must only contain the two key columns. You cannot customize this table.

What you need to do is:

  • Introduce a new entity into your model which represents the data in the join table (public class DatabaseSubject or something). You can customize this entity now as you like, for example add an IsPrimary property.
  • Remove the many-to-many mapping
  • Instead create two one-to-many relationships between DatabaseSubject and ResearchDatabase (one ResearchDatabase has many DatabaseSubjects) and between DatabaseSubject and Subject (one Subject has many DatabaseSubjects).

A more detailed description of such a scenario is here: Create code first, many to many, with additional fields in association table

Community
  • 1
  • 1
Slauma
  • 175,098
  • 59
  • 401
  • 420
  • Thank you. After more investigation, I was starting to come to the same conclusion. Thanks for providing some steps, and the link to the other post. Now, it is time to do a little refactoring! – adimauro Sep 15 '11 at 04:24