【问题标题】:How to Clone POCO entity and add to context如何克隆 POCO 实体并添加到上下文中
【发布时间】:2011-04-25 10:54:29
【问题描述】:

我正在使用 EF4,并且我已经使用我的数据库结构中的代理创建了 POCO 对象。我有一个 POCO(对象),它与其他实体有很多关系。

我使用 DataContractSerializer 和 BinaryFormatter 创建了一个对象的深层副本,我们称之为 clonedObject。

用于克隆的函数是:

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);
  }

}

现在我已经克隆了对象,如何将它添加到上下文中?如何将其添加到数据库中?

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

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

以下是我的一些做法和收到的错误。

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);

错误:

ex = {"无法添加或附加对象,因为其 EntityReference 的 EntityKey 属性值与此对象的 EntityKey 不匹配。"}

请帮忙,我在这上面花了太多时间。谢谢。

【问题讨论】:

  • 请不要走序列化路线,除非您确切知道自己在做什么,根据经验我知道这需要对您生成的代码进行大量修改才能使其正常工作。

标签: c# entity-framework entity-framework-4 clone poco


【解决方案1】:

我需要克隆我的实体,以便在表单上重新显示数据,以便用户可以选择“创建和添加类似”,以减少用户需要的工作量expend 以便将一系列类似的项目添加到我的数据库中。

我检查了一些选项,包括反射和序列化,但它们对于我想要实现的目标很混乱,然后我发现我可以克服“XYZ 是对象关键信息的一部分并且不能修改”的问题 - 即插入(保存更改)后将我的实体主键设置为 0 - 使用以下代码:

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;

【讨论】:

    猜你喜欢
    • 2016-03-17
    • 1970-01-01
    • 2012-07-06
    • 2012-07-22
    • 1970-01-01
    • 2011-05-09
    • 1970-01-01
    • 1970-01-01
    • 2018-02-05
    相关资源
    最近更新 更多