Reputation: 339
I'm working on ASP.NET MVC 4.5 site using EF. I have code that checks if a record in the DB exists, and if it doesn't it creates a new record. As a result of a problem in my code which I've subsequently fixed I was calling this code twice within a fraction of a second. The result was that a duplicate record was created. Here is my code:
Word wordToUpdate = context.Words.SingleOrDefault(w => w.Label == word);
if (wordToUpdate == null) // word doesn't exist yet so make a new one
{
Word w = new Word() {
// add new word stuff here
};
context.Words.Add(w);
}
else
{
// word already exists so just add stuff to existing entry
wordToUpdate.AnnotationGroups.Add(ag);
}
context.SaveChanges();
If the word doesn't already exist in the DB it is added twice. Here are the timestamps from the duplicate records:
CreatedOn 2014-03-11 06:52:35.743 2014-03-11 06:52:50.637
I've stepped through the code while watching the DB records and the new record is added during the first execution, so:
context.Words.SingleOrDefault()
returning null on the second execution when there is a matching record in the DB?EDIT
Let me add a few details I've observed while debugging this with a breakpoint at the beginning of the code snippet above:
wordToUpdate
is null and a new word is added.context.SaveChanges()
and checked the DB - a new row shows up with the new word addedwordToUpdate
returns null even though DB already contains that word and thus a duplicate entry for that word is added (I'm not using the word as the primary key and I'd rather handle this in code instead of trying the handle errors thrown from the DB)context.SaveChanges
is called again another row is add to the DBSo my question is since this call is coming from the same client is the code actually being executed synchronously? The way it steps through the code in debugging seems to suggest this, but this is where my knowledge of ASP.NET gets a little fuzzy.
Upvotes: 3
Views: 986
Reputation: 4259
Maybe your problem is with the assertion you are using: w => w.Label == word
.
If you are comparing objects, even though they might have same contents, ==
just compares if they have the same memory address, which is the default implementation. You should override Equals in the Word class so the behavior compares key values or something like that.
Upvotes: 1