I have 2 models as follows.
Box
DocketDetail
A DocketDetail can have upto 3 boxes associated with it (the first one being mandatory, the second two are optional). The DocketDetail model has this relationship defined as follows.
[ForeignKey("Box1Id")]
public Box Box1 { get; set; }
public Guid Box1Id { get; set;}
[ForeignKey("Box2Id")]
public Box Box2 { get; set; }
public Guid? Box2Id { get; set;}
[ForeignKey("Box3Id")]
public Box Box3 { get; set; }
public Guid? Box3Id { get; set;}
I also have the following Fluent API script to set the relationship as optional
modelBuilder.Entity<DocketDetail>()
.HasOne(dd => dd.Box1)
.WithMany()
.OnDelete(DeleteBehavior.Restrict);
modelBuilder.Entity<DocketDetail>()
.HasOne(dd => dd.Box2)
.WithMany()
.HasForeignKey(dd => dd.Box2Id)
.IsRequired(false)
.OnDelete(DeleteBehavior.NoAction);
modelBuilder.Entity<DocketDetail>()
.HasOne(dd => dd.Box3)
.WithMany()
.HasForeignKey(dd => dd.Box3Id)
.IsRequired(false)
.OnDelete(DeleteBehavior.NoAction);
However, the EF migration generates the foreign keys as mandatory. What am I missing to make these relationships optional?
migrationBuilder.AddForeignKey(
name: "FK_DocketDetail_Box_Box1Id",
table: "DocketDetail",
column: "Box1Id",
principalTable: "Box",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_DocketDetail_Box_Box2Id",
table: "DocketDetail",
column: "Box2Id",
principalTable: "Box",
principalColumn: "Id");
migrationBuilder.AddForeignKey(
name: "FK_DocketDetail_Box_Box3Id",
table: "DocketDetail",
column: "Box3Id",
principalTable: "Box",
principalColumn: "Id");