gpt4 book ai didi

c# - 如何创建 Entity Framework 模型第一个关联表?

转载 作者:行者123 更新时间:2023-11-29 23:08:19 24 4
gpt4 key购买 nike

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

文章之间有 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)

现在该结构已存在于数据库中,我们可以将 Article 表和 ArticleAssociation 表导入到 .edmx model 中。 。导入完成后,模型中的表将如下所示: enter image description here

请注意,ArticleAssociation 表本身不存在,并且它生成为“关联”类型。我们现在可以通过传统方式通过导航属性访问关联的对象:

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();
}

关于c# - 如何创建 Entity Framework 模型第一个关联表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28191819/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com