0

我有3個表:Book,Section和Content。我想添加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] 

我加入FKS這個結表。所以實體框架可以理解聯結表,並在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 
+0

我有一個解決方法。但它不是實用的解決方案。我創建了一個擁有id,BookId和PageNo列的頁表。我從Section和Content表中刪除了PageNo列。此外,我添加了一個名爲PageId的新列,它與Page表的id列相關。 – oruchreis 2011-12-25 00:52:05

回答

0

我使用EF Code First解決了這個問題。我已經將所有表格實現爲一個類,EF處理所有多對多關係。