问题
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 the DbContext, it throws a ModelValidationException
:
One or more validation errors were detected during model generation:
\tSystem.Data.Entity.Edm.EdmEntityType: : EntityType 'StudentExam' has no key defined. Define the key for this EntityType.
\tSystem.Data.Entity.Edm.EdmEntitySet: EntityType: EntitySet 'StudentExams' is based on type 'StudentExam' that has no keys defined.
I tried changing the StudentExam
class' properties 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 Role 'StudentExam_Student_Source' in relationship 'StudentExam_Student'. Because the Dependent Role properties are not the key properties, the upper bound of the multiplicity of the Dependent Role must be '*'. \tSystem.Data.Entity.Edm.EdmAssociationEnd: : Multiplicity is not valid in Role 'StudentExam_Exam_Source' in relationship 'StudentExam_Exam'. Because the Dependent Role properties are not the key properties, the upper bound of the multiplicity of the Dependent Role must be '*'.
Is there any way to achieve this in with data annotations (I don't like using the fluent API when I can use data annotations; The fluent API leads to messy code.
回答1:
It is not about data annotations or fluent api but about incorrectly defined classes - relations defined in your classes cannot be mapped at all because they are not valid at relational level. You must modify 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; }
}
Once you have this relations defined you can use your data annotations for defining keys in StudentExam
class and it will work.
Btw. fluent api doesn't lead to messy code. Messy code is created by programmer, not by API. Data annotations in turn violates POCO principle.
来源:https://stackoverflow.com/questions/10573284/relationship-mapping-table-with-additional-properties