简体   繁体   中英

Foreign key invalid with Entity Framework

So i am trying to create a table with a foreign key, but it always says that it cannot find the foreign key. heres the code:

 public class Tecnologies
    {
        [Key]
        public int TecId { get; set; }
        [Required]
        public String Name { get; set; }
    }

this one works, then i try to create this one:

 public class UserTecnologies
    {
        [Key]
        public int UserTecId { get; set; }
        [ForeignKey("Id")]
        public UserProfile User { get; set; }
        [ForeignKey("TecId")]
        public virtual Tecnologies Tecnology { get; set; }
        [Required]
        public int Rating { get; set; }
    }

and it gives me the error :

The ForeignKeyAttribute on property 'Tecnology' on type 'ESW_CloddOffice.Models.UserTecnologies' is not valid. The foreign key name 'TecId' was not found on the dependent type 'ESW_CloddOffice.Models.UserTecnologies'. The Name value should be a comma separated list of foreign key property names.

The names are correct, what am i missing ?

Okay, i found what i was doing wrong. Heres the correct code:

  public class UserTecnologies
    {
        [Key]
        public int UserTecId { get; set; }
        [ForeignKey("UserProfile")]
        public virtual int UserProfileId { get; set; }
        [ForeignKey("Tecnology")]
        public virtual int TecnologyId { get; set; }

        public virtual Tecnologies Tecnology { get; set; }
        public virtual UserProfile UserProfile { get; set; }

        [Required]
        public int Rating { get; set; }
    }

Was creating the foreign key the wrong way .

The ForeignKey attribute requires that an actual property on the entity match the name you pass in. It doesn't just tell EF what to call the key at the database level.

You either need to actually add a TecId property:

public int TecId { get; set; }

Or use fluent configuration, instead:

modelBuilder.Entity<UserTechnologies>() 
.HasRequired(c => c.Technology)
.WithMany() 
.Map(m => m.MapKey("TecId"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM