Problem creating foreign key in entity

0

I'm trying to create a primary key composite, so far so good. With this I need to do a foreign key .

I have more or less the following scenario (it's a hypothetical scenario but it reflects what I need and my error):

public class Keys {
    [Key, Column(Order = 0)]
    public int Key_1 { get; set; }

    [Key, Column(Order = 1)]
    public int Key_2 { get; set; }

    // order is important here as defined in "KeyAuthorities" table
    [ForeignKey("KeyAuthorities", Column(Order = 0)]
    public int KeyAuthorities_Key_1 { get; set; }

    [ForeignKey("KeyAuthorities", Column(Order = 1)]
    public int KeyAuthorities_Key_2 { get; set; }

}

public class KeyAuthorities {
    [Key, Column(Order = 0)]
    public int KeyAuthorities_Key_1 { get; set; }

    [Key, Column(Order = 1)]
    public int KeyAuthorities_Key_2 { get; set; }

}
  

The ForeignKeyAttribute on property 'KeyAuthorities' on type   'PortalAdmCC.Models.Keys' is not valid. The foreign key name   'KeyAuthorities' was not found on the dependent type   'PortalAdmCC.Models.Keys'. The Name value should be the comma separated   list of foreign key property names.

What does this error mean?

    
asked by anonymous 01.03.2018 / 19:25

1 answer

0

The error indicates that EF did not find the property with the name that you defined as FK in the annotation.

You can try adding a navigation property to FK:

public class Keys {
    [Key, Column(Order = 0)]
    public int Key_1 { get; set; }

    [Key, Column(Order = 1)]
    public int Key_2 { get; set; }

    // order is important here as defined in "KeyAuthorities" table
    [ForeignKey("Authorities")]
    public int KeyAuthorities_Key_1 { get; set; }

    [ForeignKey("Authorities")]
    public int KeyAuthorities_Key_2 { get; set; }

    public KeyAuthorities Authorities { get; set; }
}

public class KeyAuthorities {
    [Key, Column(Order = 0)]
    public int KeyAuthorities_Key_1 { get; set; }

    [Key, Column(Order = 1)]
    public int KeyAuthorities_Key_2 { get; set; }

}

The other option of specifying FK with annotations would be to note the navigation property with the field names that form FK:

public class Keys {
    [Key, Column(Order = 0)]
    public int Key_1 { get; set; }

    [Key, Column(Order = 1)]
    public int Key_2 { get; set; }

    // order is important here as defined in "KeyAuthorities" table
    public int KeyAuthorities_Key_1 { get; set; }

    public int KeyAuthorities_Key_2 { get; set; }

    [ForeignKey("KeyAuthorities_Key_1, KeyAuthorities_Key_2")]
    public KeyAuthorities Authorities { get; set; }
}

public class KeyAuthorities {
    [Key, Column(Order = 0)]
    public int KeyAuthorities_Key_1 { get; set; }

    [Key, Column(Order = 1)]
    public int KeyAuthorities_Key_2 { get; set; }

}
    
01.03.2018 / 19:50