如何首先使用代码向链接表添加列 [英] How to add a column to a link table with code first

查看:66
本文介绍了如何首先使用代码向链接表添加列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个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属性.
  • 删除多对多映射
  • 相反,在DatabaseSubjectResearchDatabase(一个ResearchDatabase有很多DatabaseSubject)之间以及在DatabaseSubjectSubject(一个主题有很多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 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

这篇关于如何首先使用代码向链接表添加列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆