Davio
Davio

Reputation: 4737

Updating the same Entity after calling SaveChanges causes Exception with EF5

I have an entity which I need to save twice. The first time is to set the ID. This ID needs to be filled to calculate a signature and that signature is stored back to the entity.

See the following code:

var newEntity = new MyEntity 
    { 
        \\ set values 
    };

using (var db = MyContainer.CreateContainer())
{
    db.MyEntity.Add(newEntity);
    // Call SaveChanges() to set the ID.
    db.SaveChanges();

    // I need to do some calculation on the entity
    myEntity.Signature = CalculateSignature(myEntity);
    db.SaveChanges(); // <--- This causes the exception
}

This piece of code causes an InvalidOperationException, namely The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects.

I don't understand, am I not allowed to save the same entity twice? How would I go about achieving this?

Upvotes: 0

Views: 1954

Answers (2)

user247702
user247702

Reputation: 24202

I'm guessing that CalculateSignature creates a context too. Take a look at Entity Framework Multiple Object Contexts

Upvotes: 2

Doug
Doug

Reputation: 6518

This usually occurs where you are not using a shared context between objects.

Do you load a record with a context and then pass it to a repository?

Do you have a repository that then is creating a new context to save rather than using the parent context?

I would recommend investigating a design pattern like the "Unit of work" pattern where you use a shared DbContext for all queries.

http://blogs.msdn.com/b/adonet/archive/2009/06/16/using-repository-and-unit-of-work-patterns-with-entity-framework-4-0.aspx

Upvotes: 0

Related Questions