【问题标题】:Many-to-many relationships on a specific column for Entity Framework实体框架的特定列上的多对多关系
【发布时间】:2011-12-24 23:31:59
【问题描述】:

我有 3 个表格:Book、Section 和 Content。我想在部分和内容之间添加多对多关系。 Section 和 Content 表有一个 PageNo 列。一个页面可能有许多内容和许多部分。简而言之:

Book 1----* Section (on BookId)
Book 1----* Content (on BookId)
Section *-----* Content (on PageNo)

对于 Section 和 Content 表,PageNo 不是唯一的。所以我不能在 Sql Server 中为 PageNo 添加外键。

我尝试像这样创建一个联结表:

SectionContent: [SectionId, ContentId]

我为这个联结表添加了 FK。因此实体框架可以理解联结表,并在 SectionId 和 ContentId 上建立多对多关系。但是每次当我需要插入 Section 或 Content Table 之一时,我也必须插入 SectionContent 连接表。所以首先我必须检查联结表中是否已经有相同的记录。项目中还有很多插入操作。我必须搜索所有插入操作,并且必须添加额外的查询以插入到联结表中。

我还需要获取页面中的部分和内容。这对我来说是额外的努力。

我可以删除 Section 和 Content 表之间的关系。而且我可以在 PageNo 列上使用额外的连接查询。但我想使用实体。我想以像 Section.Contents 这样的实体方式获取内容,并且我想以与 Content.Sections 相同的方式获取 Sections。

那么我可以在没有 SQL Server 的 FK 的情况下在 PageNo 列上的 Section 和 Content 之间添加多对多关联吗?

编辑:另外,如果我使用上面的联结表,我必须执行这样的 sql 查询,不是吗?

INSERT INTO SectionContent
SELECT * FROM 
(
    SELECT Section.id AS SectionId, Content.id AS ContentId
    FROM Section
    LEFT OUTER JOIN Content
        ON Section.PageNo = Content.PageNo AND 
           Section.BookId = Content.BookId 

    UNION

    SELECT Section.id AS SectionId, Content.id AS ContentId
    FROM Section
    RIGHT OUTER JOIN Content
        ON Section.PageNo = Content.PageNo AND 
           Section.BookId = Content.BookId 
) AS T
WHERE SectionId is not NULL AND ContentID is not NULL
GROUP BY T.SectionId, T.ContentId

【问题讨论】:

  • 我有一个解决方法。但这仍然不是实际的解决方案。我创建了一个包含 id、BookId、PageNo 列的 Page 表。我从 Section 和 Content 表中删除了 PageNo 列。我还添加了一个名为 PageId 的新列,它与 Page 表的 id 列相关。

标签: sql-server entity-framework many-to-many foreign-key-relationship junction-table


【解决方案1】:

我通过使用 EF Code First 解决了这个问题。我已将所有表实现为一个类,并且 EF 处理了所有多对多关系。

【讨论】:

    猜你喜欢
    • 2017-01-28
    • 2011-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-23
    • 1970-01-01
    相关资源
    最近更新 更多