Search code examples
c#asp.netlinqlinq-to-sqlclone

Linq2Sql Clone an Object C#


tblAgreement AgreementOld = (from g in TDC.tblAgreements
                             where g.AccountID == ids.accountID && g.AgreementID == AgreementID
                            select g).SingleOrDefault();

Guid AgreementIDNew = Guid.NewGuid();
var AgreementNew = AgreementOld;
AgreementNew.AgreementID = AgreementIDNew;
AgreementNew.StatusChangeDate = DateTime.Now;
AgreementNew.CreationDate = DateTime.Now;
AgreementNew.AccountID = ids.accountID;
AgreementNew.CreatedByID = ids.userID;
TDC.tblAgreements.InsertOnSubmit(AgreementNew);

I am trying to create a new object with some same values as old object, But i am getting this error message;

Cannot add an entity that already exists.

Note: I don't want to delete OLD object. Kindly Help me I have google it but couldn't find any help or solution.


Solution

  • You need to create a new object, currently your new object is also reffering to old one:

    var AgreementNew = new Agreement();  // create a new instance
    AgreementNew.SomeProperty = AgreementOld.SomeProperty; // assign property from old to new
    AgreementNew.AgreementID = AgreementIDNew; // new proerties here
    AgreementNew.StatusChangeDate = DateTime.Now;
    AgreementNew.CreationDate = DateTime.Now;
    AgreementNew.AccountID = ids.accountID;
    AgreementNew.CreatedByID = ids.userID;
    TDC.tblAgreements.InsertOnSubmit(AgreementNew);