I have following Many-To-Many relationship between two entities RelayConfig and StandardContact
Entities:
The problem is that many-to-many relation has its own state. So if you call this:
addedContacts.ForEach(ad => relayConfig.StandardContacts.Add(ad));
You tell EF that all added contacts are new relations which will be inserted to your junction table for many to many relation but calling this:
foreach (StandardContact standardContact in relayConfig.StandardContacts) {
if (standardContact.Id > 0) {
context.Entry(standardContact).State = EntityState.Modified;
}
}
will change state of the contact entity but not the state of the relation - it is still tracked as new (btw. it cannot be modified but only added, deleted or unchanged). So when you save changes relations for all your contacts are added to junction table and if the same relation already exists in the database you will get exception (because junction table contains only two FKs which are also PK and in such case same relation = PK violation).
You also need to set state for relations by using:
var objectContext = ((IObjectContextAdapter)context).ObjectContext;
objectContext.ObjectStateManager.ChangeRelatioshipState(...);
But here comes the problem: you must differ between existing contacts which just created a new relation with existing or new relying config and also contacts which are completely new - I suggest you to handle completely new contacts separately otherwise your code will be very complex.