EF基礎知識小記五(一對多、多對多處理)
阿新 • • 發佈:2017-10-10
ble people 關系 asc tab pan ces 腳本 teacher
本文主要講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, Namevarchar(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) referencesStudent (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基礎知識小記五(一對多、多對多處理)