Efficiently Determine if EF 4 POCO Already in ObjectSet

Posted by Eric J. on Stack Overflow See other posts from Stack Overflow or by Eric J.
Published on 2010-06-06T19:47:13Z Indexed on 2010/06/06 19:52 UTC
Read the original article Hit count: 465

I'm trying EF 4 with POCO's on a small project for the first time. In my Repository implementation, I want to provide a method AddOrUpdate that will add a passed-in POCO to the repository if it's new, else do nothing (as 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 that results in a NotSupportedException as documented under Referencing Non-Scalar Variables Not Supported (bonus question: why would that not be supported?)

Just removing the Contains part and always calling AddObject results in an InvalidStateException:

An object with the same key already exists in the ObjectStateManager. The existing object is in the Unchanged state. An object can only be added to the ObjectStateManager again if it is in the added state.

So clearly EF 4 knows somewhere that this is a duplicate based on the key.

What's a clean, efficient way for the Repository to update Pocos for either a new or pre-existing object when AddOrUpdate is called so that the subsequent call to SaveChanges() will do the right thing?

I did consider carrying an isNew flag on the object itself, but I'm trying to take persistence ignorance as far as practical.

© Stack Overflow or respective owner

Related posts about POCO

Related posts about entity-framework-4