0

我有 3 个表:书籍、部分和内容。我想在部分和内容之间添加多对多关系。Section 和 Content 表有一个 PageNo 列。一个页面可能有许多内容和许多部分。简单来说:

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

PageNo 对于 Section 和 Content 表都不是唯一的。所以我不能在 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
4

1 回答 1

0

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

于 2012-03-29T20:04:18.460 回答