One-to-many mapping returns validation errors

Edited with a new situation on the proposal in the comments:

This mapping is currently

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"); } 

The result is the following database:

Episodes

Shows

However, when the seed method runs, I get this error. Since I cannot debug the value of variables from the Update-Database command line (at least as far as I know), I do not see what the property has.

Verification failed for one or more objects. For more information, see EntityValidationErrors Property.

When I add a link to the display, I get the following error:

During model generation, one or more validation errors were detected:

System.Data.Entity.Edm.EdmAssociationEnd :: multiplicity is not valid in the role "Episode_Show_Source" in relation to "Episode_Show". Since the dependent role refers to key properties, the upper bound on the plurality of the dependent role must be "1".

Relations:

  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 forgotten that causes validation errors?

Edit: just to be sure I haven't forgotten anything, this is a github project.

+4
source share
1 answer

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

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

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

For a one-to-many relationship, this should be:

 HasRequired(x => x.Show) .WithMany(x => x.Episodes) .HasForeignKey(x => x.ShowID); 
+16
source

Source: https://habr.com/ru/post/1485857/


All Articles