簡體   English   中英

如何創建實體框架模型第一關聯表?

[英]How do I create Entity Framework Model First Association Table?

我需要編寫一個DB腳本來在數據庫中創建關聯表,並在單個表中創建父子結構。 結果模型應該是這樣的: 數據庫模型

文章之間具有n對n的關系。

首先,讓我們看一下表創建本身。 為了使關聯在EF中正常工作,必須正確聲明主鍵。 如果我們沒有為關聯表聲明PK,而模型設計者將正確解釋關聯,則任何插入表的嘗試都會在.SaveChanges()上引發錯誤。

要創建模型中指定的模型,我們將使用以下代碼:

create table Article (
    articleID int not null identity(1,1),
    description varchar(500) not null
)

alter table Article add constraint PK_ArticleID
    primary key (articleID)

create table ArticleAssociation (
    associatedArticle1ID int not null,
    associatedArticle2ID int not null
)

alter table ArticleAssociation add constraint PK_ArticleAssociationID
    primary key clustered (associatedArticle1ID, associatedArticle2ID ASC)

alter table ArticleAssociation add constraint FK_AsscociatedArticle1ID
    foreign key (associatedArticle1ID) references Article (articleID)

alter table ArticleAssociation add constraint FK_AsscociatedArticle2ID
    foreign key (associatedArticle2ID) references Article (articleID)

現在,該結構已存在於DB中,我們可以將Article表和ArticleAssociation表都導入到.edmx模型中 導入完成后,模型中的表將如下所示: 在此處輸入圖片說明

請注意,ArticleAssociation表本身不存在,並且其生成為“ Association”類型。 現在,我們通常可以通過導航屬性訪問關聯的對象:

using (EFTestingEntities efso = new EFTestingEntities())
{
    Article article1 = new Article();
    article1.description = "hello";

    Article article2 = new Article();
    article2.description = "world";

    efso.Article.Add(article1);
    efso.Article.Add(article2);

    article1.Article2.Add(article2);
    article2.Article1.Add(article1);

    efso.SaveChanges();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM