I'm trying to update many to many relationship using EF code first. Whenever I update I get this error, DietaryListings in the error is the join table created by migrations:
Violation of PRIMARY KEY constraint 'PK_dbo.DietaryListings'. Cannot insert duplicate key in object 'dbo.DietaryListings'. The duplicate key value is (1, 52). The statement has been terminated.
I realize that there is already existing duplicate data in DietaryListings before the update. I just don't understand why EF isn't allowing the update using the mapped relationship between Listing
and Dietary
. Shouldn't EF be updating the relationships if they change? Do I need to manually delete duplicate records in that join table before doing an EF update to the entity?
In my MVC Controller
I'm trying to update the existing object with the model data passed from a razor view using this:
//listing = updated model from razor view
//listingExisting = listing from db service
foreach (var dietary in listing.Dietaries)
{
if (dietary.Selected)
{
listingExisting.Dietaries.Add(dietary);
}
}
listingExisting.ObjectState = Repository.Pattern.Infrastructure.ObjectState.Modified;
_listingService.Update(listingExisting);
Listing class:
public partial class Listing : Repository.Pattern.Ef6.Entity
{
public Listing()
{
this.Dietaries = new List<Dietary>();
}
public int ID { get; set; }
public string Name { get; set; }
public virtual ICollection<Dietary> Dietaries { get; set; }
}
Dietaries class:
public partial class Dietary: Repository.Pattern.Ef6.Entity
{
public Dietary()
{
this.Listings = new List<Listing>();
}
public int ID { get; set; }
public string Name { get; set; }
public virtual ICollection<Listing> Listings { get; set; }
}
I've looked at all of these links and some where helpful but didn't work: link1 link2 link3 link4 link5 link6