如何克隆POCO实体,并添加上下文 [英] How to Clone POCO entity and add to context

查看:152
本文介绍了如何克隆POCO实体,并添加上下文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用EF4,我有创建POCO从我的数据库结构代理的对象。我有一个POCO(对象),其中有很多到其他实体的关系。



我创建使用的DataContractSerializer和BinaryFormatter的对象的深层副本,并允许调用它clonedObject。<用于克隆/ p>

功能:

 公共牛逼CloneProxy< T> (T源)
{
变种DCS =新System.Runtime.Serialization
.DataContractSerializer(typeof运算(T));
字符串文件路径=Initiative.txt;使用(的FileStream文件=新的FileStream(文件路径,FileMode.Create))
{
(新的BinaryFormatter())

序列化(文件,源)。
}

context.CreateProxyTypes(新类型[] {typeof运算(倡议)}); 。使用(的FileStream文件=新的FileStream(文件路径,FileMode.Open))
{
回报率(T)

(新的BinaryFormatter())反序列化(文件);
}

}

现在,我有clonedObject,怎么我将其添加到上下文? ?我怎么把它添加到数据库中。



我对象(只是给你的POCO倡议的想法):

 倡议
{
InitI
InitName
<收缴>评论
}
评论
{
CommentI
< FK> InitI
}

这里有一些我已经收到我做的方式和错误

  cloneInit.InitI = 0。 

Data_Business.RQRMComment [] =改编新Data_Business.RQRMComment [1];

ARR = cloneInit.RQRMComments.ToArray();

的for(int x = 0; X< arr.Length; X ++)//每一个(VAR在cloneInit.RQRMComments X)
{
RQRMComment thisC = ARR [X ];
INT Y = thisC.InitI;
thisC.InitI = 0;
thisC.ID = 0;
}
Context.AddObject(倡议,cloneInit);
Context.SaveChanges(System.Data.Objects.SaveOptions.AcceptAllChangesAfterSave);



错误:




离= {对象不能添加或连接,因为它的EntityReference具有不匹配的EntityKey此对象的的EntityKey属性值。}




请帮帮忙,我已经花了太多时间在这。谢谢你。


解决方案

我有需要克隆我的实体为宗旨,以重新显示表单上的数据,以便用户可以选择创建和放大器;添加类似。在努力减少工作的用户需要,以添加范围,类似的项目,我的DB的花费金额



我查了几个选项,包括反射&安培;序列化,但它们是凌乱了什么,我想实现的,然后我发现我可以克服XYZ是对象的关键信息的一部分,并且不能被修改的问题 - 即把我的实体主键0插入后(保存更改) - 用下面的代码:

  MyDbEntities BB =新MyDbEntities(); 

//添加和放大器;保存新的条目
db.Product.AddObject(产品);
db.SaveChanges();

//复位实体
db.ObjectStateManager.ChangeObjectState(产品,System.Data.EntityState.Added);
product.ProductId = 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.

解决方案

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;

这篇关于如何克隆POCO实体,并添加上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆