views:

159

answers:

1

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?

+2  A: 

I think that the problem is with the model variable...

If you can try with:

foreach(MyModel model in models){
 var id = model.Id;
 var name = model.Name
 if(entities.my_Model.Where(p => p.Id == id).Count() == 0 )
 {
     entities.AddTo_MyModel(new MyModel()
              {Name = name, Id = id});
      }
}
entities.SaveChanges();

IMO should work correctly...

HTH.

Sunny
Absolutely right. Creating a local variable for my closure resolved the issue.
JHappoldt