CodeFirst 表之间的关联

多重性关系能够是Optional(一个属性可拥有一个单个实例或没有ui

Required(一个属性必须拥有一个单个实例spa

Many不少的(一个属性能够拥有一个集合或一个单个实例)。blog

Has方法包括以下几个:get

• HasOptionalit

• HasRequiredio

• HasManymodel

在多数状况还须要在Has方法后面跟随以下With方法之一:语法

• WithOptional方法

• WithRequired集合

• WithMany

一对多

modelBuilder.Entity<Destination>()
.HasMany(d => d.Lodgings)
.WithOptional(l => l.Destination);

Destination一对多或零对多Lodging

若是将WithOptional改为WithRequired  这将使Lodgings必须对应一个Destination,若是删除Destination将级联删除Lodgings 详细>>

关闭级联删除的方法:

如今你能够设置此关系的WillCascadeOnDelete为false:

HasRequired(l=>l.Destination)

.WithMany(d=>d.Lodgings)

.WillCascadeOnDelete(false)

 

一对一

modelBuilder.Entity<PersonPhoto>()

.HasRequired(p => p.PhotoOf)

.WithOptional(p => p.Photo);

PersonPhoto一对零或一对一Photo

 

 

多对多关系

modelBuilder.Entity<Destination>()

.HasMany(d => d.Lodgings)

.WithRequired()

.HasForeignKey(l => l.LocationId);

Destination多对多Lodging

 

modelBuilder.Entity<Help>()

.HasMany<Help>(t => t.Helps)

.WithMany()

.Map(m => { m.ToTable("RelatedHelp"); });

 

 

多对多的关系语法让我比较费解。求高手解释一下

相关文章
相关标签/搜索