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?