How to Clone POCO entity and add to context

拜拜、爱过 提交于 2019-12-08 07:39:18

问题


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.


回答1:


I have had a need to clone my Entities for the purpose of re-displaying the data on a form so that a user can choose to "Create & Add Similar" in an effort to reduce the amount of effort a user needs to expend in order to add a range of similar items to my DB.

I checked out a few options including reflection & serialization but they are messy for what I am trying to achieve, I then discovered that I can overcome the "XYZ is part of the object's key information and cannot be modified" issue - i.e. set my entities primary key to 0 after insert (Save Changes) - with the following code:

MyDbEntities bb = new MyDbEntities();

 //Add & Save new entry
 db.Product.AddObject(product);
 db.SaveChanges();

 //Reset entity
 db.ObjectStateManager.ChangeObjectState(product, System.Data.EntityState.Added);
 product.ProductId = 0;


来源:https://stackoverflow.com/questions/3934208/how-to-clone-poco-entity-and-add-to-context

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!