views:

44

answers:

0

I am using EF4 and I have create POCO objects with proxies from my database structure . I have a POCO (object) which has lots of relationships to other entities.

I created a deep copy of the object using DataContractSerializer and BinaryFormatter and lets call it clonedObject.

function used for cloning is:

public T CloneProxy<T>(T source)
{
  var dcs = new System.Runtime.Serialization
     .DataContractSerializer(typeof(T));
  string filePath = "Initiative.txt";

  using (FileStream file = new FileStream(filePath, FileMode.Create))
  {
    (new BinaryFormatter()).Serialize(file, source);
  }

  context.CreateProxyTypes(new Type[] { typeof(Initiative) });

  using (FileStream file = new FileStream(filePath, FileMode.Open))
  {
    return (T)(new BinaryFormatter()).Deserialize(file);
  }

}

Now that I have clonedObject, how do I add it to the context? how do I add it to the database?

my object (just giving you an Idea of the POCO Initiative):

Initiative
{   
InitI   
InitName    
<collection>Comments
}    
Comments    
{    
CommentI    
<FK>InitI   
}

Here are some of the way I have done and errors I have received.

cloneInit.InitI = 0;

    Data_Business.RQRMComment[] arr = new Data_Business.RQRMComment[1];

    arr = cloneInit.RQRMComments.ToArray();

    for (int x = 0; x < arr.Length; x++) //each (var x in cloneInit.RQRMComments)
    {
      RQRMComment thisC = arr[x];
      int y = thisC.InitI;
      thisC.InitI = 0;
      thisC.ID = 0;
    } 
    Context.AddObject("Initiatives", cloneInit); 
    Context.SaveChanges(System.Data.Objects.SaveOptions.AcceptAllChangesAfterSave);

Error:

ex = {"The object could not be added or attached because its EntityReference has an EntityKey property value that does not match the EntityKey for this object."}

Please help, I have spent too much time on this. Thank you.