Question

Hello I have problems with my foreign key declaration.

App compile but i cant do "add-migration" because of an error:

The ForeignKeyAttribute on property 'TypeId' on type 'Equipment.Models.Device' is not valid. The navigation property 'DeviceDictionaryId' was not found on the dependent type 'Equipment.Models.Device'. The Name value should be a valid navigation property name

Here You can see my code:

namespace Equipment.Models
{
    public class Device
    {
        public int DeviceId { get;set; }
        [Required]
        [StringLength(14)]
        public string DeviceUser { get; set; }
        [ForeignKey("DeviceDictionaryId")]
        public int TypeId { get; set; }
    }
    public class DeviceDBContext: DbContext
    {
        public DbSet<Device> Devices {get; set;}
    }

}

and second class:

namespace Equipment.Models
{
    public class DeviceDictionary
    {

        public int DeviceDictionaryId { get; set; }
        [Required]
        public string DeviceManufacturer { get; set; }
        [Required]
        public string DeviceName { get; set; }

}
     public class DeviceDictionaryDBContext : DbContext
     {
         public DbSet<DeviceDictionary> Dictionary { get; set; }
     }
}

Can anyone suggest me needed edits?

Was it helpful?

Solution

You're creating two separate DbContext objects. Try adding just one:

public class MyDbContext: DbContext
{
    public DbSet<Device> Devices {get; set;}
    public DbSet<DeviceDictionary> Dictionaries { get; set; }
}

The Context must reference both Classes so that it knows about their existence. This way it can do its work, that is, set references between those classes using foreign keys.

OTHER TIPS

Try this...

namespace Equipment.Models
{
    public class Device
    {
        public int DeviceId { get;set; }
        [Required]
        [StringLength(14)]
        public string DeviceUser { get; set; }
        [ForeignKey("DeviceDictionaryId")]
        public int DeviceDictionaryId { get; set; }
    }
    public class DeviceDBContext: DbContext
    {
        public DbSet<Device> Devices {get; set;}
    }

}

Name the property DeviceDictionaryId as opposed to TypeId to allow The EF Conventions to do their work!

EDIT:

Just noticed after seeing the other answer that you have two seperate DBContext's!

I believe you need to change

[ForeignKey("DeviceDictionaryId")]
public int TypeId { get; set; }

to

[ForeignKey("DeviceDictionary")]
public int TypeId { get; set; }

... in other words, the annotation needs to specify the table rather than the column.

As others pointed out, you only need a single DBContext, with one DbSet for each table.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top