I have two classes representing a master detail relationship, where the master object contains the details and the detail object references the master. I'm trying to use object initialization to instantiate them, but not sure how to pass the master reference into the detail... Maybe not possible, but wanted to ask.
I have the following classes:
public class Detail
{
public Detail(string type, string value, Entity entity) {...}
public string Value { get; set; }
public Master Master { get; set; }
}
public class Master
{
public string ID { get; set; }
public IEnumerable<Detail> Details{ get; set; }
}
If I want to use object initializers how can I pass the master reference into the detail instance?
List<Master> = new List<Master>()
{
new Master()
{
Details= new List<Detail>()
{
new Detail()
{
Master = ???
}
}
}
};
Disregarding the fact your code is full of errors, you can't use object initialization to reference parts of the parent graph. You either need to use a constructor, helper, setter, or set it after the fact:
Usage:
or example after the fact, since
Detailsis anIEnumerable<T>: