实体类型上已经存在具有相同名称的属性或导航-如何在Entity Framework的迁移方案中添加外键

时间:2019-01-04 08:56:10

标签: 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"

错误是:

  

无法将属性或导航“ DeviceType”添加到实体类型“设备”,因为实体类型“设备”上已经存在具有相同名称的属性或导航。

这是我的上下文课程内容

 public class MyContext: DbContext
 {
     public MyContext(DbContextOptions<MyContext> options)
        : base(options)
     { }

     public DbSet<DeviceType> DeviceTypes { get; set; }
     public DbSet<Device> Devices { get; set; }
 }

2 个答案:

答案 0 :(得分:1)

编写您的Device模型类,如下所示:

public class Device
{
    [Required]
    [DataMember(Name = "key")]
    [Key]
    public Guid Key { get; set; }


    [ForeignKey("DeviceType")]   
    public Guid DeviceTypeId { get; set; } // I assumed primary key of your `DeviceType` entity is `Guid`

    [ForeignKey("ModelType")]  
    public Guid ModelTypeId { get; set; } // I assumed primary key of your `ModelType` entity is `Guid`


    [IgnoreDataMember]
    public virtual DeviceType DeviceType { get; set; }


    [IgnoreDataMember]
    public virtual ModelType ModelType { get; set; }
}

现在生成迁移。希望一切正常。

答案 1 :(得分:1)

对于我的情况,我误用了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; }