我有这个只有外键引用的类:
public class Device
{
[Required]
[DataMember(Name = "key")]
[Key]
public Guid Key { get; set; }
[ForeignKey("DeviceType")]
[IgnoreDataMember]
public virtual DeviceType DeviceType { get; set; }
[ForeignKey("Model")]
[IgnoreDataMember]
public virtual ModelType Model { get; set; }
}
运行命令时出现错误
Add-Migration -Name "DeviceMigration"
错误是:
The property or navigation 'DeviceType' cannot be added to the entity type 'Device' because a property or navigation with the same name already exists on entity type 'Device'.
这是我的上下文类内容
public class MyContext: DbContext
{
public MyContext(DbContextOptions<MyContext> options)
: base(options)
{ }
public DbSet<DeviceType> DeviceTypes { get; set; }
public DbSet<Device> Devices { get; set; }
}
最佳答案
对于我的情况,我误用了 ForeignKey 属性:
[IgnoreMap]
public long? PLCalculationMasterId { get; set; }
[ForeignKey("PLCalculationMaster"), IgnoreMap, IgnoreDataMember]
public PLCalculationMaster PLCalculationMaster{ get; set; }
而它应该是:
[IgnoreMap]
public long? PLCalculationMasterId { get; set; }
[ForeignKey("PLCalculationMasterId"), IgnoreMap, IgnoreDataMember]
public PLCalculationMaster PLCalculationMaster{ get; set; }
关于c# - 实体类型上已存在同名的属性或导航 - 如何在 Entity Framework 的迁移场景中添加外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54035722/