hendrixchord
hendrixchord

Reputation: 5444

SaveChanges throws validation error in for loop

I've an entity Candidate

public class Candidate
{
    public int Id { get; set; }

    [Required]
    public string Name { get; set; }

    public int Age { get; set; }
}

Now I've a list of candidates and I loop through the list and save them each individually. Now some items from the list don't match the validations given on the Candidate model.

var dbContext = new TestDbContext();

var list = new List<Candidate>
{
     new Candidate { Name = "", Age = 20 },
     new Candidate { Name = "Tom" , Age = 25 }
};


foreach (var item in list)
{
     try
     {
          dbContext.Candidates.Add(item);
          dbContext.SaveChanges();
     }
     catch (Exception)
     {
          // Handle exception
     }
}

Clearly the first item will throw up a Validation Error i.e.

Name is required.

But the second item in the list clearly satisfies the validation requirements, but I once again get Validation error i.e.

Name is required.

What am I doing wrong here and why is the code behaving this way?

Upvotes: 2

Views: 979

Answers (1)

Salah Akbari
Salah Akbari

Reputation: 39976

Just add a finally block to your Try Catch like this:

try
{
    dbContext.Candidates.Add(item);
    dbContext.SaveChanges();
}
catch (Exception)
{
    // Handle exception
}
finally
{
    dbContext.Candidates.Remove(item);
}

Upvotes: 2

Related Questions