首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >实体框架核心,如何为.HasOptional配置可空的外键等效项

实体框架核心,如何为.HasOptional配置可空的外键等效项
EN

Stack Overflow用户
提问于 2021-07-08 00:04:34
回答 1查看 72关注 0票数 1

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

代码语言:javascript
复制
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; }
}

配置类

代码语言:javascript
复制
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);
    }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-07-08 01:23:01

要使可选HandheldDevice成为可空的,请将ParkingAttendantId设置为可空。另外,通过添加主键来修复您的类,并再次尝试迁移到db。如果您使用EF核心5+,则不需要任何流畅的apis

代码语言:javascript
复制
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; }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68289440

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档