List<Entity> Problem
I have this kind of code
foreach(GridViewRow row in gvTagDeductionList.Rows)
{
DeductionEntity de = new DeductionEntity();
//modify this condition, make cell number to be more dynamic
if (((CheckBox)row.Cells[2].FindControl("chkInclude")).Checked == true)
开发者_Python百科 {
//following id's are said to be in numeric format in the first place
//ede.EmployeeID = Convert.ToInt32(HttpContext.Current.Session["_newEmpID"].ToString());
ede.DeductionID = Convert.ToInt32((((Label)row.Cells[0].FindControl("lblID")).Text).ToString());
ede.CreatedBy_UserID = Convert.ToInt32(HttpContext.Current.Session["_employeeID"].ToString());
ede.UpdatedBy_UserID = Convert.ToInt32(HttpContext.Current.Session["_employeeID"].ToString());
de = e201u.GetDeductionDetails(ede.DeductionID);
e201u.InsertEmployeeDeduction(ede);
lstEntity.Add(de);
}
}
de = e201u.GetDeductionDetails(ede.DeductionID);
After the second encounter of this code inside the loop, the first record in this code lstEntity.Add(de);
will be altered and in the end i will end up with two entry in my list of the last entity get by this de = e201u.GetDeductionDetails(ede.DeductionID);
Inside the loop, you have to create the object you insert into the list again. Now you are simply inserting it, then changing it and inserting it again. You only save a reference to the object to the list, not the actual object itself. As the first line of your loop (that you have not shown), try writing ede = new ...()
according to the type of object ede is.
This same "problem" will occur for all reference based types (classes), but not for value based types (structs), since for a struct you save an actual copy of the object into the list, and not just a reference like you do for a class.
Here is an example.
public class A
{
public int Test{ get; set; }
}
Some other place in code:
List<A> list = new List<A>();
A a = new A();
for( int i = 0; i < 2; i++ )
{
a.Test = i;
list.Add(a);
}
This will end up with a list that contain two references to the same A object. So list[0].Test is 1, and list[1].Test is 1.
Some other place in code:
List<A> list = new List<A>();
for( int i = 0; i < 2; i++ )
{
A a = new A();
a.Test = i;
list.Add(a);
}
This will end up with a list that contains references to two different A objects. So list[0].Test is 0, and list[1].Test is 1.
精彩评论