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.
Shimmy
source share