I am not sure if you want to insert the related Container
s into the database along with the Item
s, or if you only want to create a relationship to already existing Container
s. The possible case that the Container
entities do not exist in the database and in your object graph you only have one Container
instance per key (multiple references to those instances are allowed) should not be a problem at all and a simple code like...
foreach (var i in LocalItemList)
{
dbContext.Items.Add(i);
}
dbContext.SaveChanges();
...should actually work without exception. So, you probably have one of the following two situations which would explain the primary key constraint violation:
The
Container
entities already exist in the database and in your object graph you only have oneContainer
instance per key (multiple references to those instances are allowed again). This is the easy case and you can solve it by using:foreach (var i in LocalItemList) { dbContext.Containers.Attach(i.Container); dbContext.Items.Add(i); } dbContext.SaveChanges();
If you have multiple
Container
instances for the same key this won't work and throw an "...an object with the same key already exists in the ObjectContext..." (or similar) exception. It also won't work if theContainer
s do not exist yet in the database (you'll probably get a foreign key constraint violation then).If you have multiple
Container
object instances with the same key in your object graph you must replace the duplicates by one unique instance per key before you attach or add the entities to the context. To make this process simpler I would remove the circular references first and then use theLocal
collection to figure out if aContainer
with the same key is already attached:foreach (var i in LocalItemList) { i.Container.Items = null; var attachedContainer = dbContext.Containers.Local .SingleOrDefault(c => c.ContainerId == i.Container.ContainerId); if (attachedContainer != null) i.Container = attachedContainer; else dbContext.Containers.Attach(i.Container); // or dbContext.Containers.Add(i.Container); // depending on if you want to insert the Container or not dbContext.Items.Add(i); } dbContext.SaveChanges();