[英]How do I create Entity Framework Model First Association Table?
I need to write a DB script which creates an association table in my database, creating a parent-child structure within a single table. 我需要编写一个DB脚本来在数据库中创建关联表,并在单个表中创建父子结构。 The resulting model should be something like this:
结果模型应该是这样的:
with n to n relation between the articles. 文章之间具有n对n的关系。
First of all, let's look at the table creation itself. 首先,让我们看一下表创建本身。 For the association to work properly in EF, it's essential that primary keys are properly declared.
为了使关联在EF中正常工作,必须正确声明主键。 If we don't declare PK for the association table, while the model designer will interpret the association correctly, any attempt to insert into the table will throw error on .SaveChanges().
如果我们没有为关联表声明PK,而模型设计者将正确解释关联,则任何插入表的尝试都会在.SaveChanges()上引发错误。
To create the model specified in the model, we're going to use following code: 要创建模型中指定的模型,我们将使用以下代码:
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)
Now that the structure exists in DB, we can import both Article table and the ArticleAssociation table into our .edmx model . 现在,该结构已存在于DB中,我们可以将Article表和ArticleAssociation表都导入到.edmx模型中 。 When the import is complete, the tables in model will look like this:
导入完成后,模型中的表将如下所示:
Note the absence of ArticleAssociation table itself, and its generation as an 'Association' type. 请注意,ArticleAssociation表本身不存在,并且其生成为“ Association”类型。 We may now access the associated objects traditionally via navigation properties:
现在,我们通常可以通过导航属性访问关联的对象:
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.