When I run a migration I get the following error:
The given key 'System.Nullable1[System.Int32] ChildId' was not present in the dictionary.
Basically I want to create a relationship for a contact with another contact, e.g. Contact1 has a relationship with Contact2 of type Employee. One Contact can have many relationships with other Contacts. There is only one relationship type for each relationship. So under Contact1 you may see 3 relationship recrods, e.g. Contact2;Supervisor, Contact2;Friend, Contact3; Dentist.
My navigation properties are wrong, but I can't figure out how to set this up. Any help would be greatly appreciated :)
Contact Model
public class Contact
{
public int Id { get; set; }
public string? FirstName { get; set; }
public string? LastName { get; set; }
[InverseProperty(nameof(Relationship.ParentId))]
public virtual ICollection Parent { get; set; }
[InverseProperty(nameof(Relationship.ChildId))]
public virtual ICollection Child { get; set; }
}
Relationship Model
public class Relationship
{
public int Id { get; set; }
[ForeignKey(nameof(Parent)), Column(Order = 0)]
public int? ParentId { get; set; }
public virtual Contact? Parent { get; set; }
[ForeignKey(nameof(Child)), Column(Order = 1)]
public int? ChildId { get; set; }
public virtual Contact? Child { get; set; }
// Navigation for the relationship type
public int? RelationshipId { get; set; }
public virtual Relationship? Relationships { get; set; }
}
Prasad RaveendranPosted Nov 23, 2023, 3:13 AM
The error message you're encountering suggests that there might be a problem with the keys or their mapping in the migration.
Let's correct the relationship setup and provide some guidance on how to configure the models:
Contact Model:
Relationship Model:
In this setup, the
Contactmodel has separate navigation properties to represent relationships where the contact is a parent or a child. TheRelationshipmodel includes foreign key properties for both the parent and child contacts.Ensure you have properly configured the relationships in your DbContext:
Make sure to adjust the relationship configurations based on your specific requirements and database setup.
Once you've updated the models and the DbContext configuration, regenerate the migration and update the database. This should resolve the issue with the key not being present in the dictionary.