"ManyToMany relationship destination must have a foreign key defined in the intermediate type"

Issue #80 resolved
Robert Nitsch created an issue

I get the following exception:

Student.Doctors: ManyToMany relationship destination must have a foreign key defined in the intermediate type

The problem appeared after I added the TeachingCompany, TeachingCompanyId and Apprentices properties.

I have the following models:

class Student : Person
{
        [ManyToMany(typeof (StudentToDoctor))]
        public List<AddressItem> Doctors { get; set; }

        [ManyToOne("TeachingCompanyId", "Apprentices")]
        public AddressItem TeachingCompany { get; set; }

        [ForeignKey(typeof (AddressItem))]
        public int TeachingCompanyId { get; set; }

        // ...
}
class StudentToDoctor
{
        [ForeignKey(typeof (AddressItem))]
        public int DoctorId { get; set; }

        [ForeignKey(typeof (Student))]
        public int StudentId { get; set; }

        // ...
}
class AddressItem : Person {
        [OneToMany("TeachingCompanyId", "TeachingCompany")]
        public List<Student> Apprentices { get; set; }

        // ...
}

And those are the complete inheritance relationships:

class Person : Address {
        // ...
}

class Address {
        [PrimaryKey, AutoIncrement]
        public int Id { get; set; }

        // ...
}

Those are not the complete models, obviously, because this is from production code. Maybe you can spot the mistake right away. Otherwise I am ready to create a minimal code example that reproduces the issue.

Comments (3)

  1. Guillermo GutiƩrrez

    Until issue #17 is implemented, it's probably incorrectly finding the Apprendices property as inverse relationship, and then failing because the foreign key is not in the right place.

    Try adding an inverse ManyToMany relationship and explicitly specify inverse properties and foreign keys to avoid automatic foreign key discovery issues:

    class Student : Person
    {
        [ManyToMany(typeof (StudentToDoctor), "StudentId", "Patients")]
        public List<AddressItem> Doctors { get; set; }
    
        [ManyToOne("TeachingCompanyId", "Apprentices")]
        public AddressItem TeachingCompany { get; set; }
    
        public int TeachingCompanyId { get; set; }
    }
    
    class StudentToDoctor
    {
        public int DoctorId { get; set; }
        public int StudentId { get; set; }
    }
    
    class AddressItem : Person {
        [OneToMany("TeachingCompanyId", "TeachingCompany")]
        public List<Student> Apprentices { get; set; }
    
        [ManyToMany(typeof (StudentToDoctor), "DoctorId", "Doctors", ReadOnly = true)]
        public List<Student> Patients { get; set; }
    }
    
  2. Log in to comment