I have been encountering an issue with inserts in EF 4.0.
During a migration from one system to another I migrate the values of three configuration tables into a database fronted by EF.
The following code crashes:
foreach (MyModel model in models)
{
if(entities.my_Model.Where(p => p.Id == model.modelId).Count() == 0 )
{
entities.AddTo_MyModel(new MyModel()
{Name = model.Name, Id = model.modelId});
}
}
entities.SaveChanges();
Note that the call to SaveChanges will crash with a constraint exception, indicating that the value of ID (PK) already exists. I am not attempting to insert duplicates.
The following code DOES run correctly.
foreach (MyModel model in models)
{
if(entities.my_Model.Where(p => p.Id == model.modelId).Count() == 0 )
{
entities.AddTo_MyModel(new MyModel()
{Name = model.Name, Id = model.modelId});
entities.SaveChanges();
}
}
Note the moved save.
Is there something I am fundamentally not understanding about EF?