2
votes

When I run application I have this error:

PossibleAnswer_Question_Source: : Multiplicity is not valid in Role 'PossibleAnswer_Question_Source' in relationship 'PossibleAnswer_Question'. Because the Dependent Role properties are not the key properties, the upper bound of the multiplicity of the Dependent Role must be '*'.

How to resolve it?

Model classes for Question and PossibleAnswer:

public class Question
    {
        public int ID { get; set; }
        public string Text { get; set; }
        public bool IsAssociatedWithProfessor { get; set; }
        public bool IsAssociatedWithAssistant { get; set; }

        public virtual ICollection<PossibleAnswer> PossibleAnswers { get; set; }
    }
public class PossibleAnswer
    {
        public int ID { get; set; }
        public string Text { get; set; }
        public int QuestionID { get; set; }

        [ForeignKey("QuestionID")]
        public virtual Question Question { get; set; }
    }

And I put this in OnModelCreating(DbModelBuilder modelBuilder):

modelBuilder.Entity<PossibleAnswer>()
               .HasRequired(f => f.Question)
               .WithRequiredDependent()
               .WillCascadeOnDelete(false);
1
Try add [Key] attribute to Question.ID property, or add [InverseProperty("ID")] to PossibleAnswer.Question - Lukas.Navratil
After that I get this: The property 'ID' cannot be configured as a navigation property. The property must be a valid entity type and the property should have a non-abstract getter and setter. For collection properties the type must implement ICollection<T> where T is a valid entity type. - bambi
Sorry, I didn't notice that you defined 1:1 relationship in your fluent mapping, so follow answer from @octavioccl... And of course, the inverse property should be [InverseProperty("PossibleAnswers ")], but it is not required when you fix the mapping and add [Key] attribute... - Lukas.Navratil

1 Answers

1
votes

The problem is you are not configuring a one-to-many relationship in the OnModelCreating method (that is a one-to-one configuration). To achieve what you want, you could do this:

modelBuilder.Entity<PossibleAnswer>()
           .HasRequired(pa => pa.Question)
           .WithMany(q=>q.PossibleAnswers)
           .HasForeignKey(pa=>pa.QuestionID)
           .WillCascadeOnDelete(false);

This way, you don't need to use the ForeignKey attribute on the Question navigation property. Is a good practice try to not merge Fluent Api with Data Annotations