c# - 实体类型上已存在同名的属性或导航 - 如何在 Entity Framework 的迁移场景中添加外键

标签 c# sql-server entity-framework migration

我有这个只有外键引用的类:

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/

相关文章:

c# - 使用属性网格修改窗体属性

c# - 当被 JSON.NET 序列化时,属性的顺序变得困惑

javascript - 从 iPad 创建 Canvas 图像

sql-server - 在 SQL Server 2008 R2/中创建新图表时出错

php - 连接mssql后utf-8无法插入mysql

sql - Microsoft SQL - 识别重复项并分配唯一标识符

c# - 当只需要一个子集时, Entity Framework 加载大表的所有记录

c# - Entity Framework 缓存问题

c# - 异步方法中的奇怪调试器行为

c# - EF Core 批量扩展 : Index was out of range on BulkInsert