如何创建 Entity Framework 模型优先协会 Table?

How do I create Entity Framework Model First Association Table?

我需要编写一个数据库脚本,在我的数据库中创建一个关联 table,在单个 table 中创建一个父子结构。生成的模型应该是这样的:

文章之间有 n 对 n 的关系。

首先,让我们看看table创作本身。要使关联在 EF 中正常工作,必须正确声明主键。如果我们不为关联 table 声明 PK,而模型设计者将正确解释关联,任何插入 table 的尝试都会在 .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)

现在数据库中已经存在该结构,我们可以将 Article table 和 ArticleAssociation table 导入我们的 .edmx model。导入完成后,模型中的 tables 将如下所示:

注意没有 ArticleAssociation table 本身,它的生成是 '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();
}