Click here to Skip to main content
15,891,704 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
It shouldn't be this hard! I am about to give up on EF...

My model has weekly newspaper Editions. Each Edition can have many Classifieds. Each Classified can appear in one or more Editions. My models:

C#
public class Classifieds
{ 
  [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
  public int ClassifiedId { get; set; }
  ...
  public virtual ICollection<EditionModel> Editions { get; set; }
}

public class EditionModel
{
  [Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
  public int EditionId { get; set; } // This is YYYYWW, WW = week number
  public DateTime PublicationDate { get; set; }
  public virtual ICollection<Classifieds> Classifieds { get; set; }
}


The OnModelCreating override:

C#
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
   modelBuilder.Entity<EditionModel>()
     .Property(z => z.EditionId)
     .HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);

   modelBuilder.Entity<EditionModel>()
     .HasMany(c => c.Classifieds)
     .WithMany(d => d.Editions)
     .Map(x =>
     {
       x.MapLeftKey("EditionId");
       x.MapRightKey("ClassifiedId");
       x.ToTable("EditionModelClassifieds");
     });
   base.OnModelCreating(modelBuilder);
}


The Create Classifieds Action code (HTTP put):

C#
public async Task<ActionResult> Create(Classifieds classifieds, int[] EditionList)
{
  var allPubs = PopulateEditionList(); // Current and next 12 editions
  classifieds.Editions = new List<EditionModel>();
  foreach (var p in EditionList)
  {
     var anEd = new EditionModel { EditionId = p }; 
     db.Set<EditionModel>().Attach(anEd);
     classifieds.Editions.Add(anEd);
  }

  ...
  if (ModelState.IsValid)
  {
     var ads = db.Classifieds.Add(classifieds);
     await db.SaveChangesAsync().ConfigureAwait(false);
     return View("Receipt", classifieds);
  }
  ...
}


On submit of a new Classifieds, I get "Violation of PRIMARY KEY constraint 'PK_dbo.EditionModels'. Cannot insert duplicate key in object 'dbo.EditionModels'."

Why does EF insist on wanting insert duplicate rows in EditionModels instead of just linking the junction table row to an existing row therein? I get this error even if I select an Edition which does not yet exist in EditionModels. How do I get around this?
Posted

1 solution

The problem was that EditionModel was not part of the context. Thank you, Slauma for pointing me in the right direction. The corrected Create Action is:

C#
...
classifieds.Editions = new List();
foreach (var p in EditionList)
{
   var ed = await db.EditionModel.FindAsync(p);
   if (ed == null)
      ed = new EditionModel { EditionId = p, PublicationDate = (from q in allPubs where                      q.EditionId == p select q).Single().PublicationDate };
   InsertOrUpdate(ed);
   classifieds.Editions.Add(ed);
}
...


The rest of the code is as above.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900