K.Z
K.Z

Reputation: 5075

Entity Framework Core, how to configure nullable foreign key equivalent for .HasOptional

I need to configure optional / nullable foreign key. In my scenario, ParkingAttendant has a 0:* relationship with HandHeldDevice. I have put the configuration class but not sure if that is correct?

enter image description here

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; }
}

Configuration class

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);
    }
}

Upvotes: 1

Views: 762

Answers (1)

Serge
Serge

Reputation: 43959

To make optional HandheldDevice make ParkingAttendantId as nullable . Also fix your classes by adding primary keys and try to migrate to db again. If you use EF core 5+ you don't need any fluent apis for this

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; }
}

Upvotes: 1

Related Questions