2

I am trying to push 100 Product entities created dynamically, using DBSet.AddRange().

If for example, 1st Product entity has some data issues and throws exception during Commit(), all remaining 99 product entities also not going to save.

Is it possible to skip corrupted entities only so that other entities can be saved using DBSet.AddRange() ?

Alexander
  • 4,153
  • 1
  • 24
  • 37
Jaish Mathews
  • 766
  • 1
  • 9
  • 25
  • if you are using mvc you could try `ModelState.IsValid` on your `Model` after that individually add them and commit as suggested below by Richard – Eldho Apr 11 '16 at 09:29
  • Data is coming through a flat file. A background process will read this file to create DTO&Entities and will dump to the database. As of some constraints, we need to do this DB operations through EF only. – Jaish Mathews Apr 11 '16 at 15:47
  • After reading the file , you can create DTO of valid objects, this validation should done in business and attach the valid entities to the context. As @Richard you cannot validate in ef context – Eldho Apr 11 '16 at 15:52

2 Answers2

3

You cannot do this with EF, you have to change your logic and validate the entities yourself before adding them to the EF context. Alternatively, you have to add them individually and commit after each one, but that will be much less efficient.

Richard
  • 29,854
  • 11
  • 77
  • 120
  • Data is coming through a flat file. A background process will read this file to create DTO&Entities and will dump to the database. So is there a way to validate the entity in this scenario of non UI background process? – Jaish Mathews Apr 11 '16 at 15:49
  • Your scenario doesn't change anything, you simply check manually whether the entity is valid, and add it to your context if so. You will not be able to get EF to do this bit for you - it will fail if *any* of the entities are invalid (as it should). – Richard Apr 11 '16 at 16:12
1

Since it is impossible to skip the invalid entities. I would personally do this.

  1. I first try to do an AddRange,
  2. Then handle an exception, that when it fails to add a batch, do one by one.

At least this way, you can balance it out.

try
{
    await entities.AddRange(batch);
    await unitOfWork.Save();
}
catch (Exception ex)
{
    await SaveEntities(batch);
}

public void SaveEntities(List<Entity> entities)
{
    foreach (var item in entities)
    {
        // add one by one.
    }
}
ggeorge
  • 1,496
  • 2
  • 13
  • 19