I think I’m running into a common problem:
I would like to try to insert an object to the database. If primary key is violated then I would like to abort the insert. (this is an example, the question really applies to any kind of error and any of the CRUD operations)
How can I discard changes made to EF context?
I can’t afford recreating it every time something goes wrong.
PS. I know that perhaps I could check if everything is ok eg. by querying the db, but I don’t like the idea. Db constraints are there for some reason and this way it’s faster and I have to write less code.
You can detach inserted entity from
ObjectContext. You can also useObjectStateManagerand its methodGetObjectStateEntries. InObjectStateEntryyou can modify its state.The problem is that you are not using technology in supposed way:
Sure you should because your code doesn’t prevent such situations.
Yes indeed you should check if everything is OK. Calling database to “validate” your data is something that DBAs really like (sarcasm). It is your responsibility to achieve the highest possible validity of your data before you call
SaveChanges. I can imagine that many senior developers / team leaders would simply not pass your code through their code review. And btw. in the most cases it is not faster because of inter process or network communication.