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:
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; }
public DateTime PublicationDate { get; set; }
public virtual ICollection<Classifieds> Classifieds { get; set; }
}
The OnModelCreating override:
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):
public async Task<ActionResult> Create(Classifieds classifieds, int[] EditionList)
{
var allPubs = PopulateEditionList();
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?