如何首先使用代码向链接表添加列 [英] How to add a column to a link table with code first
问题描述
我有一个ResearchDatabase实体,该实体与Subject实体具有多对多关系.即研究数据库属于一个或多个学科类别,而学科类别包含一个或多个研究数据库.
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.
在我的ResearchDatabaseConfiguration文件中,我具有以下映射:
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.
现在,我收到了一个新的规范.每个主题的研究数据库的顺序将按字母顺序排列,最相关的是第一条(按照用户的看法),其次是第二组如果找不到,也可以尝试这些"数据库,也按字母顺序.因此,基本上,我需要另一列来表示数据库是在第一组还是第二组中.诸如IsPrimary列之类的内容,或链接表本身内部的内容.我希望这是有道理的.
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?
推荐答案
这是不可能的.多对多联接表由Entity Framework在内部进行管理,并且它只能包含两个关键列.您无法自定义此表.
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.
您需要做的是:
- 在模型中引入一个新实体,该实体表示联接表中的数据(
public class DatabaseSubject
或类似内容).您现在可以根据需要自定义此实体,例如添加IsPrimary
属性. - 删除多对多映射
- 相反,在
DatabaseSubject
和ResearchDatabase
(一个ResearchDatabase有很多DatabaseSubject)之间以及在DatabaseSubject
和Subject
(一个主题有很多DatabaseSubject)之间创建两个一对多关系.
- 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 anIsPrimary
property. - Remove the many-to-many mapping
- Instead create two one-to-many relationships between
DatabaseSubject
andResearchDatabase
(one ResearchDatabase has many DatabaseSubjects) and betweenDatabaseSubject
andSubject
(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
这篇关于如何首先使用代码向链接表添加列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!