0

Database build error:

One or more validation errors were detected during model generation:

Key_Authorities_Source_Key_Authorities_Target: : The number of properties in the Dependent and Principal Roles in a relationship constraint must be identical.

Key Class:

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

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

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

    public string Name { get; set; }

    public string Description { get; set; }

    [ForeignKey("Id"), Column(Order = 1)]
    public virtual ICollection<KeyAuthorities> Authorities { get; set; }
}

Key Authorities Class:

[Table("Key_Auths")]
public class KeyAuthorities
{
    [Key, Column(Order = 0)]
    public int Id { get; set; }
    
    [Key, Column(Order = 1)]
    public int KeyId { get; set; }
    
    public int DoorId { get; set; }

    public int VehicleId { get; set; }

    public int GateId { get; set; }
}

Why doesn't this set this foreign key?

1
  • This model can't work. EF doesn't allow ICollection (non-generic) in a navigation property. Jan 24, 2022 at 18:13

2 Answers 2

1

The error message is actually telling you that the number of properties don't match. This is because your Key class is uniquely identified by 3 properties (the 3 PK that you define: Id, OwnedByFId and OwnedByUId), but you're trying to define a Foreign Key to your Key Class using only the Id.

You must set all the PKs on your foreign class:

[Table("Key_Auths")]
public class KeyAuthorities
{
    [Key, Column(Order = 0)]
    public int Id { get; set; }

    [Key, Column(Order = 1)]
    [ForeignKey("Id, OwnedByFId, OwnedByUId")]
    public int KeyId { get; set; }

    public int DoorId { get; set; }
    
    public int VehicleId { get; set; }

    public int GateId { get; set; }
}

Notice that I added the data annotation [ForeignKey("Id, OwnedByFId, OwnedByUId")].

0
// error message is basically telling that you have 
// not configured the keys and their order properly in "Keys" table

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 virtual ICollection KeyAuthorities { 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; }

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.