This is the first time I am trying to use EF 4 with POCO in a small project. In my implementation of the Repository, I want to provide the AddOrUpdate method, which will add the passed POCO to the repository, if it is new, otherwise do nothing (since the updated POCO will be saved when SaveChanges is called).
My first thought was to do this:
public void AddOrUpdate(Poco p) { if (!Ctx.Pocos.Contains<Poco>(p)) { Ctx.Pocos.AddObject(p); } }
However, this leads to a NotSupportedException , as described in NotSupportedException to non-scalar variables is not supported (bonus question: why won't it be supported?)
By simply deleting the Contains part and always calling AddObject results in an InvalidStateException :
An object with the same key already exists in the ObjectStateManager. The existing facility is in an unchanged state. An object can only be added to the ObjectStateManager again if it is in the added state.
It's so clear that EF 4 knows somewhere that this is a key-based duplicate.
What is a clean and efficient way for the Repository to update Pocos for a new or pre-existing object when calling AddOrUpdate so that the subsequent call to SaveChanges () does the right thing?
I actually considered carrying the isNew flag on the object itself, but I try to make persistence ignorance as practical.
source share