有人可以帮助我使用此代码,它可以更改selected_deparmtents列表中某个部门的Lft和Rgt属性。我遇到的问题是获取临时变量中的旧值或先前值,该变量保存先前的部门Lft和Rgt属性。它的作用是显示temp.Lft属性的更新值,这是错误的我希望以前的Lft属性进行计算。有谁知道如何解决这个问题
int counter = 0;
int lft = department.Lft;
int rgt;
Department temp;
List<Department> clones = new List<Department>(selected_departments);
foreach (Department dept in selected_departments)
{
if (counter < 1)
{
rgt = (dept.Rgt - dept.Lft);
dept.Lft = lft;
dept.Rgt = lft + rgt;
}
else
{
temp = clones.ElementAt(counter - 1); // <-- incorrect
// previous departments value should be old value
lft = lft + (dept.Lft - temp.Lft);// here temp.Lft always show the newly updated value
rgt = lft + (dept.Rgt - dept.Lft);
dept.Lft = lft;
dept.Rgt = rgt;
}
db.Entry(dept).State = EntityState.Modified;
db.SaveChanges();
counter++;
}
答案 0 :(得分:4)
问题是,您实际上并没有在clones
List
中获得足够深的副本。相反,它有一个对部门的所有引用的副本,因此当您更新一个时,它会更改两者中的值。
假设您的Department
构造函数为左右参数:
List<Department> clones = new List<Department>(selected_departments.Count);
for (int i = 0; i < selected_departments.Count; i++)
{
clones.Add(new Department(selected_departments[i].Lft, selected_departments[i].Rgt));
}