如何创建实体框架模型第一关联表?

时间:2015-01-28 12:03:01

标签: c# mysql sql entity-framework ef-model-first

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

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

1 个答案:

答案 0 :(得分:0)

首先,让我们看一下表创建本身。要使关联在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 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();
}