c# - 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);
}
}
一切正常,除了更新迁移后出现一个新属性 -SpecializationName1
在Employees
表中。另外一个是FK,原来不是,这更奇怪。我完全不知道如何修复它,因为它几乎是自己做的,我从来没有输入SpecializationName1
过代码。
解决方案
有趣的是,您似乎遇到了 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);
推荐阅读
- airflow - 如何毫不拖延地安排执行?
- c - 如何将这些函数放在 Headers (C) 中
- python - django.db.utils.OperationalError: no such table: MainApp_user 当我尝试创建超级用户时
- csv - 如何从谷歌云平台下载表格
- go - 打破悬挂式扫描仪的正确方法是什么?
- c++-actor-framework - 在 Visual Studio 中使用 Actor 框架
- javascript - 查找数组中每个数字的频率
- ios - UIKit:如何使用以编程方式创建的约束为约束更改设置动画?
- python - 如何在 knn 算法中使用加权标签?
- reactjs - 如何更改 React-big-calendar 中组件事件的默认道具?