转载MS官方文档:https://msdn.microsoft.com/zh-cn/data/jj591620
Configuring Relationships with the Fluent API
在EFCodeFirst Entity类写完后, 关系代码写在DBConetx类文件中
配置一:
1对0/1对1关系----Configuring a Required-to-Optional Relationship (One-to–Zero-or-One)
个人理解:单向关联??强弱关联??(Required有强引用,需要的意思,Optional有弱引用,可选的意思)
下代码分别: 配置主键; 配置主键及外键
// Configure the primary key for the OfficeAssignment
modelBuilder.Entity<OfficeAssignment>()
.HasKey(t => t.InstructorID); // Map one-to-zero or one relationship
modelBuilder.Entity<OfficeAssignment>()
.HasRequired(t => t.Instructor)
.WithOptional(t => t.OfficeAssignment);
配置二:
1对1关系----Configuring a Relationship Where Both Ends Are Required (One-to-One)
个人理解:双向关联,但不确定这里的 Required/Optianal 是什么意思
HasRequired --- WithRequiredPrincipa or WithRequiredDependent (both ends of the relationship are required)
HasOptianal --- WithOptionalPrincipal or WithOptionalDependent (both ends of the relationship are required)
// Configure the primary key for the OfficeAssignment
modelBuilder.Entity<OfficeAssignment>()
.HasKey(t => t.InstructorID); modelBuilder.Entity<Instructor>()
.HasRequired(t => t.OfficeAssignment)
.WithRequiredPrincipal(t => t.Instructor);
配置三:
多对多----Configuring a Many-to-Many Relationship
文中说明:CourseInstructor table is created with Course_CourseID and Instructor_InstructorID columns
modelBuilder.Entity<Course>()
.HasMany(t => t.Instructors)
.WithMany(t => t.Courses)
文中说明:generates the CourseInstructor table with CourseID and InstructorID columns
modelBuilder.Entity<Course>()
.HasMany(t => t.Instructors)
.WithMany(t => t.Courses)
.Map(m =>
{
m.ToTable("CourseInstructor");
m.MapLeftKey("CourseID");
m.MapRightKey("InstructorID");
});
疑问
配置四:
配置导航属性----Configuring a Relationship with One Navigation Property
区别: 与配置一相比,少了WitOptional(t=>tofficeAssignment)
与配置二相比,WithRequiredPrincipal() 中少了t => t.Instructor
官方说明:if want a one-to-one relationship between Instructor and OfficeAssignment, where you have a navigation property on only the Instructor type
// Configure the primary Key for the OfficeAssignment
modelBuilder.Entity<OfficeAssignment>()
.HasKey(t => t.InstructorID); modelBuilder.Entity<Instructor>()
.HasRequired(t => t.OfficeAssignment)
.WithRequiredPrincipal();
配置五:
级联删除----Cascade Delete