I'm writing an ASP.NET MVC 4 web app. I'm using DbContext.ValidateEntity
to check whether or not about-to-be-added entities pass some checks. Checks like whether or not their custom Name
property is unique, or other properties pass my custom logic.
My unit tests have spotted some behavior that I didn't expect, though. I'm using the repository pattern and I have a global DbContext
that I use and pass into my repository functions for retrieving EF model entities from the database.
Up front, the problem is that inside of ValidateEntity
, when looking at an entity that is being added, I query for all pre-existing entities and make sure that a particular field meets passes some uniqueness checks of mine. But, in the pre-existing items that I query, I already see the item being added.
So for example, if no entities exist in the database and I am creating the first one, I will see it in ValidateEntity
if I query for all existing entities.
I thought that SaveChanges
called ValidateEntity
for all entities in the collection, prior to submitting them to the database?