码迷,mamicode.com
首页 > 其他好文 > 详细

EF基础知识小记五(一对多、多对多处理)

时间:2017-10-10 20:41:53      阅读:235      评论:0      收藏:0      [点我收藏+]

标签:模型设计   people   技术   action   png   es2017   外键约束   bsp   har   

本文主要讲EF一对多关系和多对多关系的建立

一、模型设计器

1、一对多关系

右键设计器新增关联

技术分享

技术分享

导航属性和外键属性可修改

2、多对多关系

右键设计器新增关联

技术分享

技术分享

模型设计完毕之后,根据右键设计器根据模型生成数据库,就能生成对应的表之间的一对多和多对多关联

 

二、代码层面

建表语句如下:

--建表脚本
create table Student
(
    Id int not null,
    Name varchar(30) not null,
    Age int not null
)
create table Teacher
(
    Id int not null,
    Name varchar(30) not null,
    Age int not null
)

create table StudentTeacher
(
    StudentId int not null,
    TeacherId int not null
)

create table InfoCard
(
    Id int not null,
    [Money] int not null,
    StudentId int not null
)

添加常规主键约束,代码如下:

--单主键约束
alter table Student add constraint [PK_People]
primary key clustered (Id Asc)

alter table InfoCard add constraint [PK_InfoCard]
primary key clustered (Id Asc)

alter table Teacher add constraint [PK_Teacher]
primary key clustered (Id Asc)

 

1、一对多(通过外键)

--但外键约束(一对多)
alter table InfoCard add constraint [FK_InfoCard_Student]
foreign key (StudentId) references Student (Id) on delete no action on update no action

 

2、多对多(中间表双主键双外键)

--双主键约束(多对多)
alter table StudentTeacher add constraint [PK_StudentTeacher]
primary key clustered (StudentId,TeacherId Asc)

--双外键约束(多对多)
alter table StudentTeacher
add constraint [FK_StudentTeacher_Student]
foreign key (StudentId) references Student (Id) on delete no action on update no action --级联更新级联删除

alter table StudentTeacher add constraint [FK_StudentTeacher_Teacher]
foreign key (TeacherId) references Teacher (Id) on delete no action on update no action 

生成对应的一对多和多对多关联的表之后,根据数据库生成模型就能生成对应的模型

 

EF基础知识小记五(一对多、多对多处理)

标签:模型设计   people   技术   action   png   es2017   外键约束   bsp   har   

原文地址:http://www.cnblogs.com/GreenLeaves/p/7647178.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!