Quando si utilizza ObjectContext la risposta fornita da QuantumHive non funziona.
L'errore riscontrato in questa situazione è:
An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.
System.InvalidOperationException: An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.
at System.Data.Objects.ObjectStateManager.AddEntry(IEntityWrapper wrappedObject, EntityKey passedKey, EntitySet entitySet, String argumentName, Boolean isAdded)
at System.Data.Objects.ObjectContext.AddSingleObject(EntitySet entitySet, IEntityWrapper wrappedEntity, String argumentName)
at System.Data.Objects.DataClasses.RelatedEnd.AddEntityToObjectStateManager(IEntityWrapper wrappedEntity, Boolean doAttach)
at System.Data.Objects.DataClasses.RelatedEnd.AddGraphToObjectStateManager(IEntityWrapper wrappedEntity, Boolean relationshipAlreadyExists, Boolean addRelationshipAsUnchanged, Boolean doAttach)
at System.Data.Objects.DataClasses.RelatedEnd.Add(IEntityWrapper wrappedTarget, Boolean applyConstraints, Boolean addRelationshipAsUnchanged, Boolean relationshipAlreadyExists, Boolean allowModifyingOtherEndOfRelationship, Boolean forceForeignKeyChanges)
at System.Data.Objects.DataClasses.RelatedEnd.Add(IEntityWrapper wrappedEntity, Boolean applyConstraints)
at System.Data.Objects.DataClasses.EntityReference`1.set_ReferenceValue(IEntityWrapper value)
at System.Data.Objects.DataClasses.EntityReference`1.set_Value(TEntity value)
Per clonare correttamente un oggetto Entity Framework (almeno in EF6.0) è:
/// <summary>
/// Clone a replica of this item in the database
/// </summary>
/// <returns>The cloned item</returns>
public Item CloneDeep()
{
using (var context = new EntityObjectContext())
{
var item = context.Items
.Where(i => i.ItemID == this.ItemID)
.Single();
context.Detach(item);
item.EntityKey = null;
item.ItemID = 0;
return item;
}
}
Che dire di ValueInjecter? Sfortunatamente, fa una copia superficiale, non profonda. http://valueinjecter.codeplex.com –
Puoi mostrarci la tua classe di modello? In caso contrario, è un POCO? Ha proprietà complesse? –
appena finito di leggere, prima di pensare, direi, caricare poi staccare e avrai la tua copia pronta per l'inserimento. Ora dobbiamo parlare di tipo complesso come suggerito da @GeorgeVovos – tschmit007