I use EF Core 7.0.3.
Here is my entity:
[Table("Common_T230")]
public class Employment
{
[Column("F230_ID")]
public int Id { get; set; }
[Column("F230_14")]
public string VehicleNumber { get; set; }
public virtual Vehicle Vehicle { get; set; }
}
And here are the definitions for the relationship:
modelBuilder.Entity<Employment>()
.HasOne(e => e.Vehicle)
.WithMany()
.HasPrincipalKey(e => e.VehicleNumber)
.HasForeignKey(e => e.VehicleNumber);
Now when I load the employment and set the VehicleNumber (the foreign key value) and set the navigation property to null, ctx.SaveChanges() will change null to F230_14 (VehicleNumber).
Can someone explain to me why this happen? VehicleNumber contains a valid foreign key value.
var employment = query.Include(x => x.Vehicle)
.FirstOrDefault(x => x.Date == currentDate
&& x.ProjectNumber == projectNumber);
employment.PersonelNumber = personelNumber;
employment.Vehicle = null;
employment.VehicleNumber = vehicleNumber ?? "";
// here, EF Core will save null to F230_14 (VehicleNumber)
ctx.SaveChanges();
When you set the navigation property to NULL, you are saying that "this object does not have an associated Vehicle", thus there is no foreign key value. There might be scenarios (e.g. lazy loading) where you start with a foreign key value but no object (I have not used EF in a while), but if you explicitly set the object to NULL, I would expect it to set the FK value to NULL as well.