2015-02-24 92 views
0
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); 

我想創建一個與舊對象具有相同值的新對象,但我收到此錯誤消息;Linq2Sql克隆一個對象C#

無法添加已存在的實體。

注意:我不想刪除舊對象。請幫助我我有谷歌它,但找不到任何幫助或解決方案。

回答

1

您需要創建一個新的對象,目前新對象也reffering到老:

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

我知道這個解決辦法,但其如此頭疼! – 2015-02-24 07:59:29

+1

@WaqarAhmed你必須這樣做,其參考類型,這樣的方式將無法正常工作 – 2015-02-24 09:13:22

0

如果AgreementOld是數據表,然後就去做

var AgreementNew = AgreementOld.Copy();