简体   繁体   中英

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. The resulting model should be something like this: 数据库模型

with n to n relation between the articles.

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. 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().

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM