1

Why isn't the exception triggered? Linq's "Any()" is not considering the new entries?

MyContext db = new MyContext();

foreach (string email in {"asdf@gmail.com", "asdf@gmail.com"})
{
   Person person = new Person();
   person.Email = email;

   if (db.Persons.Any(p => p.Email.Equals(email))
   {
       throw new Exception("Email already used!");
   }

   db.Persons.Add(person);
}

db.SaveChanges()

Shouldn't the exception be triggered on the second iteration?

The previous code is adapted for the question, but the real scenario is the following:
I receive an excel of persons and I iterate over it adding every row as a person to db.Persons, checking their emails aren't already used in the db. The problem is when there are repeated emails in the worksheet itself (two rows with the same email)

4

3 に答える 3

1

への呼び出しdb.Personsは常にデータベース クエリをトリガーしますが、それらの新しい Person はまだデータベースに永続化されていません。

于 2013-11-12T16:41:13.383 に答える