我需要配置可选/可空的外键。在我的场景中,ParkingAttendant与HandHeldDevice的关系是0:*。我已经设置了configuration类,但不确定是否正确?

public class HandheldDevice
{
// other properties
public int ParkingAttendantId { get; set; }
public ParkingAttendant ParkingAttendants { get; set; }
}
public class ParkingAttendant
{
public ParkingAttendant()
{
this.HandheldDevices = new HashSet<HandheldDevice>();
}
// other properties
public ICollection<HandheldDevice> HandheldDevices { get; set; }
}配置类
public class HandHeldDeviceConfiguration : IEntityTypeConfiguration<HandheldDevice>
{
public void Configure(EntityTypeBuilder<HandheldDevice> builder)
{
builder.ToTable("mytable", "dbo");
builder.HasKey(column => column.HandHeldId);
builder
.HasOne(handHeldDevice => handHeldDevice.ParkingAttendants)
.WithMany(pakingAttendant => pakingAttendant.HandheldDevices)
.HasForeignKey(handHeldDevice => handHeldDevice.ParkingAttendantId)
.IsRequired(false);
}
}发布于 2021-07-08 01:23:01
要使可选HandheldDevice成为可空的,请将ParkingAttendantId设置为可空。另外,通过添加主键来修复您的类,并再次尝试迁移到db。如果您使用EF核心5+,则不需要任何流畅的apis
public class HandheldDevice
{
public int Id { get; set;
public int? ParkingAttendantId { get; set; }
public virtual ParkingAttendant ParkingAttendant { get; set; }
}
public class ParkingAttendant
{
public int Id { get; set;
public ParkingAttendant()
{
this.HandheldDevices = new HashSet<HandheldDevice>();
}
public virtual ICollection<HandheldDevice> HandheldDevices { get; set; }
}https://stackoverflow.com/questions/68289440
复制相似问题