I have this method that receives a list of type VentasLinias
and inserts each record in the DB
public void InsertLines(int idVenta , List<VentasLinias> listVentas)
{
foreach (VentasLinias vl in listVentas)
{
db.VentasLinias.Add(vl);
db.SaveChanges();
i++;
}
}
I have 2 doubts about this, the first is, do SaveChanges()
I do it for iteration or when leaving the loop?
The other question is that when I try to save it gives me this error:
An exception of type 'System.Data.Entity.Validation.DbEntityValidationException' occurred in EntityFramework.dll but was not handled in user code
Additional information: Validation error for one or more entities. See the 'EntityValidationErrors' property for more details.
If I debug the exception I see this but I don't see any clue as to which field is failing me.
Thank you,
He
db.SaveChanges()
must go outside theforeach
. The reason is that for each call toSaveChanges()
, EF creates a transaction and persists the pending changes in the context, that is, if you do it in each iteration, you will be making n connections to the DB instead of only making a single transaction with all theINSERT
About
EntityvalidationError
it is because you have some validation error in the entity you are trying to save, if you add the code of the classVentasLinias
we could see what the problem is