I would like to clone a quote by plugin but it fails with "Cannot insert duplicate key row in object 'dbo.QuoteBase' with unique index 'ndx_Unique_Quote'. The duplicate key value is redacted".
I am trying to simply copy the entity to an new one and create that one. I am aware of the problematic with primary key field so i remove the old guid in property id and the attributes list. I am also replacing the values of Money/EntityReference/OptionSetValue-fields with a function i found in antoher thread to prevent conflicts there.
Heres my code - "OriginalQuote.record" is the orginal entity retrieved by:
Entity record = client.Retrieve(
((EntityReference)context.InputParameters["Target"]).LogicalName,
((EntityReference)context.InputParameters["Target"]).Id,
new ColumnSet(true)
);
The function i use for replacing sepecial attributes:
public static Entity CloneEntitySandbox(Entity entityToClone)
{
var newEntity = new Entity(entityToClone.LogicalName);
var systemAttributes = new List();
systemAttributes.Add("createdon");
systemAttributes.Add("createdby");
systemAttributes.Add("modifiedon");
systemAttributes.Add("modifiedby");
systemAttributes.Add("owninguser");
systemAttributes.Add("owningbusinessunit");
foreach (var attribute in entityToClone.Attributes
.Where(x => x.Key != entityToClone.LogicalName "id")
.Where(x => !systemAttributes.Contains(x.Key)))
{
switch (attribute.Value.GetType().Name)
{
case "Money":
var m = attribute.Value as Money;
newEntity[attribute.Key] = new Money(m.Value);
break;
case "EntityReference":
var er = attribute.Value as EntityReference;
newEntity[attribute.Key] = new EntityReference(er.LogicalName, er.Id);
break;
case "OptionSetValue":
var os = attribute.Value as OptionSetValue;
newEntity[attribute.Key] = new OptionSetValue(os.Value);
break;
default:
newEntity[attribute.Key] = attribute.Value;
break;
}
}
return newEntity;
}
The cloning logic itself:
Entity newQuote = CloneEntitySandbox(OriginalQuote.record);
//Set the EntityState to null, so that a new cloned record can be created
newQuote.EntityState = null;
//remove the PrimaryId of the record otherwise will show you error
newQuote.Attributes.Remove(newQuote.LogicalName "id");
newQuote.Attributes.Remove("sit_vorgang");
newQuote.Id = Guid.NewGuid();
newQuote.Attributes["name"] = " (copy)";
tracingService.Trace("newQuote.name: " newQuote.Attributes["name"]);
tracingService.Trace("newQuote.Id: " newQuote.Id.ToString());
client.Create(newQuote);
What could cause these problems?