Errors when inserting records using EF

5

I have this method that receives a list of type VentasLinias and inserts each record in the database

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 one is, does the SaveChanges() do it for iteration or when leaving the loop?

The other doubt is that when I try to save I get this error:

  

An exception of type 'System.Data.Entity.Validation.DbEntityValidationException' occurred in EntityFramework.dll but was not controlled in the user's 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 do not see any clue as to which field is failing me.

Thank you,

    
asked by ilernet 24.05.2017 в 17:31
source

1 answer

6

The db.SaveChanges() must go outside the foreach . The reason is that for every call to SaveChanges() , EF creates a transaction and persists the pending changes in context ie if you do it in each iteration you will be making n connections to the DB instead of performing just a single transaction with all INSERT

About EntityvalidationError is because you have some validation error in the entity that you are trying to save, If you add the code of the class VentasLinias we could see what the problem is

    
answered by 24.05.2017 / 17:44
source