Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Property or navigation with the same name already exists on entity type - how to add foreign keys in migration scenario of Entity Framework

I have this class with only the foreign key references:

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; }
}

I get an error while running the command

 Add-Migration -Name "DeviceMigration"

Error is:

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'.

This is my context class content

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

     public DbSet<DeviceType> DeviceTypes { get; set; }
     public DbSet<Device> Devices { get; set; }
 }
like image 561
kudlatiger Avatar asked Mar 04 '23 19:03

kudlatiger


2 Answers

For my situation, I misused ForeignKey attribute:

[IgnoreMap]
public long? PLCalculationMasterId { get; set; }
[ForeignKey("PLCalculationMaster"), IgnoreMap, IgnoreDataMember]
public PLCalculationMaster PLCalculationMaster{ get; set; }

whereas it should have been:

[IgnoreMap]
public long? PLCalculationMasterId { get; set; }
[ForeignKey("PLCalculationMasterId"), IgnoreMap, IgnoreDataMember]
public PLCalculationMaster PLCalculationMaster{ get; set; }
like image 112
Oğuzhan Kahyaoğlu Avatar answered Mar 27 '23 03:03

Oğuzhan Kahyaoğlu


Write your Device model class as follows:

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; }
}

Now generate the migration. Hope everything will work fine.

like image 41
TanvirArjel Avatar answered Mar 27 '23 04:03

TanvirArjel