Linq2Sql 克隆对象 C#
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);
我正在尝试创建一个与旧对象具有相同值的新对象,但我收到此错误消息;
Cannot add an entity that already exists.
注意:我不想删除旧对象。请帮助我,我有 google 但找不到任何帮助或解决方案。
您需要创建一个新对象,目前您的新对象也引用了旧对象:
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);
如果 AgreementOld 是 DataTable 则直接执行
var AgreementNew = AgreementOld.Copy();
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);
我正在尝试创建一个与旧对象具有相同值的新对象,但我收到此错误消息;
Cannot add an entity that already exists.
注意:我不想删除旧对象。请帮助我,我有 google 但找不到任何帮助或解决方案。
您需要创建一个新对象,目前您的新对象也引用了旧对象:
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);
如果 AgreementOld 是 DataTable 则直接执行
var AgreementNew = AgreementOld.Copy();