One-to-Many relationship mapping returns validation errors
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);
Jeroen Vannevel
Graduated with a Bachelors in Applied Computer Science at the University College of Ghent. I focus heavily on C#, Roslyn, Entity-Framework and the general Microsoft ecosystem. Having trouble following best practices? Take a look at VSDiagnostics! Curriculum Vitae LinkedIn Programming is the art of telling another human what one wants the computer to do. ~Donald Knuth
Updated on June 03, 2022Comments
-
Jeroen Vannevel almost 2 years
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:
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.