Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One-to-Many relationship mapping returns validation errors

Edited with the new situation per suggestion in the comments:

Currently I have this mapping

public ShowMap() {
        ToTable("Shows");
        HasKey(x => x.ShowID);

        Property(x => x.ShowID)
            .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity)
            .IsRequired()
            .HasColumnName("ShowID");
}

public EpisodeMap() {
        ToTable("Episodes");
        HasKey(x => x.EpisodeID);

        Property(x => x.EpisodeID)
        .IsRequired()
        .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity)
        .HasColumnName("EpisodeID");

        Property(x => x.ShowID)
            .IsRequired()
            .HasColumnName("ShowID");

        Property(x => x.EpisodeNumber)
            .IsRequired()
            .HasColumnName("EpisodeNumber");
}

This results in the following database:

Episodes

Shows

However, when the seed method is run I receive this error. Since I can't debug the value of variables from the command line command Update-Database (at least, not as far as I know) I can't see what the property holds.

Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.

When I add the relationship to the mapping, I receive the following error:

One or more validation errors were detected during model generation:

System.Data.Entity.Edm.EdmAssociationEnd: : Multiplicity is not valid in Role 'Episode_Show_Source' in relationship 'Episode_Show'. Because the Dependent Role refers to the key properties, the upper bound of the multiplicity of the Dependent Role must be '1'.

Relationship:

        HasRequired(x => x.Show)
            .WithMany(x => x.Episodes)
            .HasForeignKey(x => x.EpisodeID);

This is the model:

public class Episode {
  public int EpisodeID {get; set;}
  public int ShowID {get; set;}
  public int EpisodeNumber {get; set;}
  public virtual Show Show { get; set; }
}

public class Show {
  public int ShowID {get; set;}
  public virtual ICollection<Episode> Episodes { get; set; }
}

What have I overlooked that causes validation errors?

Edit: just to be certain I haven't forgotten anything, this is the project on github.

like image 416
Jeroen Vannevel Avatar asked Jun 12 '13 17:06

Jeroen Vannevel


1 Answers

This is the problem (from your git repository, class EpisodeMap):

HasRequired(x => x.Show)
    .WithMany(x => x.Episodes)
    .HasForeignKey(x => x.EpisodeID);

EpisodeID is the PK in Episode and EF expects a one-to-one mapping in this case without an Episodes collection but an Episode reference instead ("upper bound of multiplicity = 1").

For a one-to-many relationship it has to be:

HasRequired(x => x.Show)
    .WithMany(x => x.Episodes)
    .HasForeignKey(x => x.ShowID);
like image 185
Slauma Avatar answered Nov 07 '22 08:11

Slauma