我有这段代码,它没有任何理由地复制,我的问题是当我尝试更改“NewRow”中的值时,它会自动复制到“CurRow”,我想创建“CurRow”的副本,并且每一行都有不同的值在“Gmtrs.weight”中。
var CurRow = db.Fold_Trans.AsNoTracking().First(x => x.ID == Id);
List<Fold_Trans> LsFoldTrans = [CurRow];
var OrgGmtrs = decimal.Parse(TxtOrgGMtrs.EditValue);
var TpMtrs = decimal.Parse(TxtTPGMtrs.EditValue);
var BalMtrs = decimal.Parse(OrgGmtrs - TpMtrs);
var OrgWt = decimal.Parse(TxtOrgWt.EditValue);
var OrgAvgWt = decimal.Parse(TxtOrgAvgWt.EditValue);
var TpWt = decimal.Parse(OrgAvgWt * TpMtrs);
var BalWt = decimal.Parse(OrgWt - TpWt);
var NewRow = CurRow;
CurRow.ID = Id;
CurRow.Gmtrs = BalMtrs;
CurRow.Weight = BalWt;
int ExCn = 1;
string NewPieceNo = CurRow.Piece + @$"-TP{ExCn}";
string NewMainPieceNo = CurRow.MainPiece + @$"-TP{ExCn}";
NewRow.Piece = NewPieceNo;
NewRow.MainPiece = NewMainPieceNo;
NewRow.Gmtrs = TpMtrs;
NewRow.Weight = TpWt;
NewRow.ID = 0;
LsFoldTrans.Add(NewRow);
db.Fold_Trans.AddUpdateOrDeleteCommRange(LsFoldTrans, x => x.ID == Id);
db.SaveChanges();
如何防止这种行为?我需要做什么才能在整个项目中不再发生这种情况?
我正在将 .NET 8 与 EF Core 和 SQL Server 结合使用。
您遇到的问题是因为 NewRow 引用与 CurRow 相同的对象。在 C# 中,当您将一个对象分配给另一个对象时,它们都会引用相同的内存位置。要创建对象的真实副本,您需要克隆它。由于 Fold_Trans 是一个实体框架实体,因此您可以手动创建该对象的深层副本。
以下是如何创建 CurRow 副本的示例:
以下是修改后的代码:
var CurRow = db.Fold_Trans.AsNoTracking().First(x => x.ID == Id);
List<Fold_Trans> LsFoldTrans = new List<Fold_Trans> { CurRow };
var OrgGmtrs = decimal.Parse(TxtOrgGMtrs.EditValue.ToString());
var TpMtrs = decimal.Parse(TxtTPGMtrs.EditValue.ToString());
var BalMtrs = OrgGmtrs - TpMtrs;
var OrgWt = decimal.Parse(TxtOrgWt.EditValue.ToString());
var OrgAvgWt = decimal.Parse(TxtOrgAvgWt.EditValue.ToString());
var TpWt = OrgAvgWt * TpMtrs;
var BalWt = OrgWt - TpWt;
// Clone the CurRow object to create a new instance for NewRow
var NewRow = CloneFoldTrans(CurRow);
CurRow.Gmtrs = BalMtrs;
CurRow.Weight = BalWt;
int ExCn = 1;
string NewPieceNo = CurRow.Piece + @$"-TP{ExCn}";
string NewMainPieceNo = CurRow.MainPiece + @$"-TP{ExCn}";
NewRow.Piece = NewPieceNo;
NewRow.MainPiece = NewMainPieceNo;
NewRow.Gmtrs = TpMtrs;
NewRow.Weight = TpWt;
NewRow.ID = 0;
LsFoldTrans.Add(NewRow);
db.Fold_Trans.AddUpdateOrDeleteCommRange(LsFoldTrans, x => x.ID == Id);
db.SaveChanges();
Fold_Trans CloneFoldTrans(Fold_Trans source)
{
return new Fold_Trans
{
// Copy all the properties from source to new instance
Piece = source.Piece,
MainPiece = source.MainPiece,
Gmtrs = source.Gmtrs,
Weight = source.Weight,
// Copy other properties as needed
// Ensure not to copy the ID if you want a new row in the database
// Exclude any properties that should not be copied
// You may also want to include any navigation properties if needed
};
}
在此代码中: