You can pass an instance of Batch
to the constructor of Instruction
, and then store a reference to that Batch
that you can expose with a property. (This was already shown in another answer - I'm repeating it because it provides context to what I'm going to add next.)
class Instruction
{
public Instruction(Batch parent)
{
Parent = parent;
}
public Batch Parent { get; private set; }
public string InstructionUID { get; set; }
}
Now Instruction
has a Parent
property that returns a Batch
.
But there's a gap. If you call
var parent = batch.Instruction[0].Parent
is parent == batch
? It looks like that's the intent. The Instruction
contains a reference to the Batch
that contains it.
But nothing is enforcing that. For example, I could do this:
someBatch.Instruction[0] = someOtherBatch.Instruction[1];
Now someBatch
contains an array of Instruction
, but at least one of them actually has someOtherBatch
as its parent.
Maybe that possibility is no big deal, but I think that if Parent
is meant to refer to the Batch
containing the Instruction
but it might not, then you haven't actually accomplished what you're aiming for.
I'd recommend creating a separate class that contains both a Batch
and an Instruction
. (Perhaps ParentInstructionRelation
?)
public class ParentInstructionRelation
{
Batch Parent {get;private set;}
Instruction Instruction {get;private set;}
public ParentInstructionRelation(Batch parent, Instruction instruction)
{
Parent = parent;
Instruction = instruction;
}
}
That way Instruction
doesn't need a reference to its parent. It probably shouldn't have a reference to its parent. What if the same Instruction
is in two different instances of Batch
? Which one is the parent?
But if Batch
needs to expose an Instruction
and a reference to itself, then it can do that by returning a ParentInstructionRelation
. Or a class that reads the Instruction
from Batch
can create that relationship.
var instructions = batch.InstructionArray
.Select(instruction => new ParentInstructionRelation(batch, instruction));