【问题标题】:Entity Framework Core, how to configure nullable foreign key equivalent for .HasOptionalEntity Framework Core,如何为 .HasOptional 配置可空外键等效项
【发布时间】:2021-09-18 04:49:12
【问题描述】:

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

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

【问题讨论】:

  • 这里看不出有什么问题,你这里有一对多(或零)的关系

标签: c# .net-core entity-framework-core


【解决方案1】:

要使可选的 HandheldDevice 使 ParkingAttendantId 为 nullable 。还可以通过添加主键来修复您的类并尝试再次迁移到 db。如果您使用 EF core 5+,则不需要任何流利的 api

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

【讨论】:

    猜你喜欢
    • 2016-06-04
    • 2022-09-22
    • 2017-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-07
    • 1970-01-01
    • 2021-02-04
    相关资源
    最近更新 更多