2

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?

9
  • 2
    once you add an item, it is still in dbContext; remove that items in Catch when you get an exception Commented May 4, 2016 at 20:07
  • I've to do a dbContext.Candidates.Remove(item) ??? Commented May 4, 2016 at 20:08
  • or you can have var dbContext = new TestDbContext(); inside for loop Commented May 4, 2016 at 20:11
  • no that won't work for me, I make use of repositories and stuff :) Commented May 4, 2016 at 20:13
  • did Removing work? Commented May 4, 2016 at 20:13

1 Answer 1

2

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);
}
Sign up to request clarification or add additional context in comments.

3 Comments

Will it be committed? I didn't try, but I think you have to call SaveChanges after Remove(), don't you?
@AliaksandrBortnik Well the code inside a finally block will get executed regardless of whether or not there is an exception so if you call SaveChanges after Remove it also removes the items from DB which have inserted correctly in the try block and this is not what we want. We just need to remove that item from dbContext so that the catch block will not rethrow an exception.
That's right, makes sense. Cleanup just for a context. Not sure about your plan if it has not been added to a context successfully.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.