0

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?

Davio
  • 4,609
  • 2
  • 31
  • 58

2 Answers2

2

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

Community
  • 1
  • 1
user247702
  • 23,641
  • 15
  • 110
  • 157
  • You were right, the signature calculation creates a context too. This is because the entity is serialized before the calculation is done. This serialization is also called from another place when data needs to be transferred and at that point it needs a context to load its navigation properties. – Davio Oct 05 '12 at 13:28
0

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

Doug
  • 6,460
  • 5
  • 59
  • 83