I'm desperate. I have seen a lot of answers about this issue, but does not work for me.
My method takes an object type Operation and a list of machines. The object Operation has an idMachine. Now, I need create a List Operation where there are many items as number of machines in list and each element has an idMachine different. The problem is that each element have the same idMachine, and this is the last assigned.
In my first approach I did:
public void SetOperationCreatedBulk(Operation op, List<Machines> listMachines){
List<Operation> listOp = new List<Operation>();
foreach(var machine in listMachines) {
op.idMachine = machine.idMachine; // assign the corresponding id
listOp.Add(op); // add modify op to list
}
// do something whith listOp...
}
Soon I found out that it's not possible change the list value into foreach-loop and I read this answer where advises use for-loop
Then I did:
public void SetOperationCreatedBulk(Operation op, List<Machines> listMachines){
List<Operation> listOp = new List<Operation>();
for (int i = 0; i < listMachines.Count; i++) {
op.idMachine = listMachines[i].idMachine;
// listOp[i] = op; // trigger exception, although I do 'List<Operation> listOp = new List<Operation>(listMachines.Count);'
listOp.Add(op);
}
// do something whith listOp...
}
I understand that the problem is the reference to object Operation. I'm working all time in the same reference. I have tried to create an auxiliar Operation object into loop but I have get the same result.
Thanks for your time.