SaveChanges在for循环中抛出验证错误

时间:2016-05-04 20:05:22

标签: c# asp.net-mvc entity-framework entity-framework-6

我是一个实体Candidate

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

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

    public int Age { get; set; }
}

现在我已经列出了candidates,我遍历列表并逐个保存。现在,列表中的某些项目与Candidate模型上提供的验证不匹配。

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
     }
}

显然,第一项会引发验证错误,即

  

名称是必需的。

但是列表中的第二项显然满足验证要求,但我再次得到验证错误,即

  

名称是必需的。

我在这里做错了什么,为什么代码会这样?

1 个答案:

答案 0 :(得分:1)

只需向您的finally Try添加Catch个屏障,如下所示:

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