title: How to change GUID of entity before saving back to database (in C#)
body: <p>We have code to serialize entities to file:</p>
  
  <pre><code>formatter.Serialize(fileStream, session); // BinaryFormatter
  </code></pre>
  
  <p>and to deserialize:</p>
  
  <pre><code>session = (Session)binaryFormatter.Deserialize(innerStream);
  </code></pre>
  
  <p>The entity structure is quite complicated and if necessary I can come up with a simpler example, however the crux of the problem is this.  There is a Patient table that has multiple "Sessions".  The Patient has an associated table "Cities", and therein lies the problems.  Each computer has it's own Database (SQLServer Express) and has a table Cities which contain exactly the same data (London, Madrid, Berlin).  However, on each machine, the unique key for the city (a GUID) is different!  When I deserialize a session on another machine from which it was serialized on, I want to use the same city based on name, NOT Guid.
  The deserialization works fine.  It's the deserialized entity to the database that causes me grief.  To get the City GUID correct, I use:</p>
  
  <pre><code>session.Patient.City.CityGUID = tempCity.CityGUID;
  session.Patient.CityGUID = tempCity.CityGUID;    
  </code></pre>
  
  <p>tempCity is the entity from the database with the matching name (like 'London').</p>
  
  <p>I can do this, but on the line:</p>
  
  <pre><code>context.Patients.Attach(session.Patient);
  </code></pre>
  
  <p>I get an exception of the form:</p>
  
  <pre><code>[System.InvalidOperationException] = {System.InvalidOperationException: The property 'CityGUID' is part of the object's key information and cannot be modified. 
  at System.Data.Entity.Core.Objects.EntityEntry.DetectChangesInProperty(Int32 ordinal, Boolean detectOnlyComplexProperties, Boolea...
  </code></pre>
  
  <p>Any ideas on how to fix this?  I can create whole new objects but this is problematic because if I deserialize two sessions that both have the same patient, they should remain that way in the new database.  My creating new entities, I end up with 2 new patients.</p>
  
  <p>I think the best solution is to make sure the Cities have the same GUIDs on different machines, perhaps by modifying the install set, but I'm wondering if there is a simple fix.</p>
  
  <p>Opinions?</p>
  
  <p>Dave</p>