代码优先外键引用相同功能的 EF Core 7 中的主键

问题描述 投票:0回答:1

我的这个类有 2 个字段,一个作为主键,另一个是外键:

public partial class CCSSubCuenta
{
    [Key]
    [Required]
    [MaxLength(6)]
    [Column("SCTA_CLAVE", TypeName = "decimal(6)")]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public decimal SctaClave { get; set; }

    [MaxLength(6)]
    [Column("SCTA_CLAVE_SCTA_MAESTRA", TypeName = "decimal(6)")]
    public decimal? SctaClaveSctaMaestra { get; set; }
}

我尝试使用

[ForeignKey("SCTA_CLAVE")]
来引用主键,但在部署迁移时它不起作用。

通过数据注释或 Fluent API 定义外键的正确方法是什么?

c# .net entity-framework-core ef-code-first
1个回答
0
投票

您不能在外键属性上使用

[ForeignKey]

[ForeignKey]
是装饰一个导航属性来指示 外键列 :

public class File
{
    public int Id { get; set; }
    public string Name { get; set; }
    [ForeignKey("FolderId")]
    public Folder? Folder { get; set; } // Navigation Property
}

或者 外键属性 :

public class File
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int FolderId { get; set; } // Foreign Key Property
    [ForeignKey(nameof(FolderId))]
    public Folder? Folder { get; set; } // Navigation Property
}

它还可以装饰集合导航属性,但这是另一个主题。


在 EF Core 中,定义关系的是导航属性。但你的模型没有导航属性。

您需要使用导航属性定义关系,例如:

public partial class CCSSubCuenta
{
    [Key]
    ...
    public decimal SctaClave { get; set; }

    [MaxLength(6)]
    [Column("SCTA_CLAVE_SCTA_MAESTRA", TypeName = "decimal(6)")]
    public decimal? SctaClaveSctaMaestra { get; set; }

    [ForeignKey(nameof(SctaClaveSctaMaestra))]
    public CCSSubCuenta? SctaClaveSctaMaestraNav { get; set; }
}

如果你不想修改模型,你可以使用流畅的语法添加阴影导航属性:

public class CuentaContext : DbContext
{
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.Entity<CCSSubCuenta>()
            .HasOne<CCSSubCuenta>()
            .WithMany()
            .HasForeignKey(c => c.SctaClaveSctaMaestra);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.