I’m new to .NET MVC and I’m struggling with using Code First with an existing database in which a table has a one to none-or-one (1 -> 0..1) relationship.
I have a report, which can have many sections, and each section can have many questions. Now here’s the bit where I think I’m running into trouble… each question may have one answer or none.
I’m getting the following error:
System.Data.Edm.EdmAssociationEnd: : Multiplicity is not valid in Role
‘QuestionAnswer_Question_Source’ in relationship
‘QuestionAnswer_Question’. Because the Dependent Role properties are
not the key properties, the upper bound of the multiplicity of the
Dependent Role must be �*�.
Here are my model classes:
ModeratorReport.cs
public class ModeratorReport
{
[Key, Column(Order = 0)]
public int ModeratorReportID { get; set; }
[Key, Column(Order = 1)]
public string Status { get; set; }
public string FileYear { get; set; }
public string SessionCode { get; set; }
public string CentreNumber { get; set; }
public string SubjectNumber { get; set; }
public string PaperNumber { get; set; }
public string ModeratorNumber { get; set; }
public DateTime? DateModified { get; set; }
public virtual ICollection<AuditItem> Audit { get; set; }
}
Section.cs
public class Section
{
[Key]
public int SectionID { get; set; }
public string SectionEnglish { get; set; }
public string SectionWelsh { get; set; }
public virtual ICollection<Question> Questions { get; set; }
}
Question.cs
public class Question
{
[Key]
public int QuestionID { get; set; }
[ForeignKey("Section")]
public int SectionID { get; set; }
public string QuestionEnglish { get; set; }
public string QuestionWelsh { get; set; }
public string Type { get; set; }
public virtual Section Section { get; set; }
public virtual QuestionAnswer QuestionAnswer { get; set; }
}
QuestionAnswer.cs
public class QuestionAnswer
{
[Key]
public int AnswerID { get; set; }
[ForeignKey("ModeratorReport"), Column(Order = 0)]
public int ModeratorReportID { get; set; }
[ForeignKey("ModeratorReport"), Column(Order = 1)]
public string Status { get; set; }
[ForeignKey("Section")]
public int SectionID { get; set; }
[ForeignKey("Question")]
public int QuestionID { get; set; }
public string Answer { get; set; }
public virtual ModeratorReport ModeratorReport { get; set; }
public virtual Section Section { get; set; }
public virtual Question Question { get; set; }
}
I also have a one-to-many relationship with ModeratorReport and Audit but I don’t think that is what is causing the error.
Any help would be appreciated.
Thanks.
The EF is complaining because it sounds like you are using an FK Association – which means that the QuestionID is a property of the Entity and there is a Question reference too – and you can’t do this with FK Associations.
if you remove the
QuestionIDfromQuestionAnswerit should workI would suggest you to use fluent mapping which is more clear: