1

Sometimes I am importing 5000+ rows (of different entity types) into my DB. I use Entity Framework and I want the context to save the rows that fits on my model, if there are invalid ones they should be discarded.

I am inside a transaction, so : I need to decide at the end of the iteration if i want to Complete() the transacion or Dispose() ,It depends on which kind of entity throws the exception.

I think there are 2 possibilities:

  1. Check if a entity object is valid before context.Add(object)
  2. Add the 5000 items and, set in some way that context.SaveChanges() , saves the valid one and discard the invalid ones (now it throws an exception and discard all added items).

I am asking for a snippet of code, or some indications i can follow to solve that situation. I want only to import the valid items and generate a log of the invalid ones.

Thanks. I will mark as an answer if you solve it.

X.Otano
  • 2,079
  • 1
  • 22
  • 40

1 Answers1

2

Option 1 is the more sensible approach. Adding 5000 objects and then saving changes is very non-performant. A better approach is

 while (null != (entity = GetNextEntity())
 {
    if (entity.IsValid())
    {
        context.Add(entity);
        context.SaveChanges();
    }
 }

Update -- Ignore SQL errors

 while (null != (entity = GetNextEntity())
 {
    try
    {
        context.Add(entity);
        context.SaveChanges();
    }
    catch (Exception) { /* eat it */ }
 }
Richard Schneider
  • 34,944
  • 9
  • 57
  • 73