Relationship mapping table with additional properties?

I have three classes:

public partial class Student : Contact { //Inherited from Contact: //public int ContactId { get; set; } //public string FirstName { get; set; } //public string LastName { get; set; } public virtual StudentExam StudentExam { get; set; } } public partial class Exam { public int ExamId { get; set; } public string Title { get; set; } public DateTime Date { get; set; } public virtual StudentExam StudentExam { get; set; } } public partial class StudentExam { public byte Score { get; set; } public int ContactId { get; set; } public int ExamId { get; set; } public virtual Student Student { get; set; } public virtual Exam Exam { get; set; } } 

When trying to initialize a DbContext, it throws a ModelValidationException : One or more validation errors were detected during model generation: \ tSystem.Data.Entity.Edm.EdmEntityType :: EntityType 'StudentExam' does not have a key. Define a key for this EntityType. \ tSystem.Data.Entity.Edm.EdmEntitySet: EntityType: EntitySet 'StudentExams' is based on the StudentExam type, which does not have specific keys.

I tried changing the properties of the StudentExam class to the following:

 [Key, ForeignKey("Student"), Column(Order = 0)] public int ContactId { get; set; } [Key, ForeignKey("Exam"), Column(Order = 1)] public int ExamId { get; set; } 

Now I get this exception:

\ tSystem.Data.Entity.Edm.EdmAssociationEnd :: multiplicity is not valid in the role "StudentExam_Student_Source" in relation to "StudentExam_Student". Since the properties of a dependent role are not key properties, the upper bound on the multiplicity of the dependent role must be "*". \ tSystem.Data.Entity.Edm.EdmAssociationEnd :: multiplicity is not valid in the role "StudentExam_Exam_Source" in relation to "StudentExam_Exam". Since the properties of a dependent role are not key properties, the upper bound on the multiplicity of the dependent role must be "*".

Is there a way to achieve this using data annotations (I don't like using a free API when I can use data annotations, and a free API leads to messy code.

0
entity-framework entity-relationship ef-code-first code-first
source share
1 answer

This is not about data annotations or fluent api, but about incorrectly defined classes - relationships defined in your classes cannot be displayed at all, because they are not valid at the relational level. You must change your classes:

 public partial class Student : Contact { public virtual ICollection<StudentExam> StudentExams { get; set; } } public partial class Exam { ... public virtual ICollection<StudentExam> StudentExams { get; set; } } 

After defining these relationships, you can use data annotations to define keys in the StudentExam class, and it will work.

Btw. fluent api does not lead to messy code. Messiah code is created by the programmer, not the API. Data annotations, in turn, violate the POCO principle.

+2
source share

All Articles