首页 > 解决方案 > EF Core 代码首先自行创建附加属性

问题描述

我首先在随机示例中练习代码,这是我的代码:

public class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int SectionId { get; set; }
    public string SpecializationName { get; set; }
    public virtual Section Section { get; set; }
    public virtual Specialization Specialization { get; set; }
}

public class Specialization
{
    public string SpecializationName { get; set; }
}

public class EmployeeConfiguration : IEntityTypeConfiguration<Employee>
{
    public void Configure(EntityTypeBuilder<Employee> builder)
    {
        builder.ToTable("Employees");
        builder.Property(x => x.Name).IsRequired().HasMaxLength(100);

        builder.HasOne(x => x.Section);
        builder.HasOne(x => x.Specialization);
    }
}

public class SpecializationConfiguration : IEntityTypeConfiguration<Specialization>
{
    public void Configure(EntityTypeBuilder<Specialization> builder)
    {
        builder.ToTable("Specializations");
        builder.HasKey(x => x.SpecializationName);

        builder.Property(x => x.SpecializationName).IsRequired().HasMaxLength(20);
    }
}

一切正常,除了更新迁移后出现一个新属性 -SpecializationName1Employees表中。另外一个是FK,原来不是,这更奇怪。我完全不知道如何修复它,因为它几乎是自己做的,我从来没有输入SpecializationName1过代码。

标签: c#entity-framework-coreef-core-3.0

解决方案


有趣的是,您似乎遇到了 EF Core 3.x 错误。

SpecializationName中的属性名称Employee似乎与任何 EF Core FK 名称约定都不匹配

如果依赖实体包含名称与这些模式之一匹配的属性,则它将被配置为外键:

  • <navigation property name><principal key property name>
  • <navigation property name>Id
  • <principal entity name><principal key property name>
  • <principal entity name>Id

所以它被丢弃了,但是不知何故默认生成的FK是相同的,并且由于它是“保留的”,EF在末尾附加了后缀“1”。

像往常一样,当 EF Core 约定不起作用时,解决方案是使用显式映射,例如EmployeeConfiguration

builder.HasOne(x => x.Specialization)
    .WithMany()
    .HasForeignKey(x => x.SpecializationName);

推荐阅读