Object initialization for master/detail relationship

448 Views Asked by At

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 = ???
             } 
        }
    }
};
2

There are 2 best solutions below

5
TheGeneral On

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:

public class Master()
{
     public Master(List<Detail> details)
     {
         details.ForEach(x => x.Master = this);
         Details = details;
     }
     ...
}

Usage:

List<Master> = new List<Master>()
{
    new Master(new List<details>{...})
}

or example after the fact, since Details is an IEnumerable<T>:

list.ForEach(x => x.Details.ToList().ForEach(y => y.Master = x));
3
Aluan Haddad On

You can do this by implementing a Master.Details as a full property that sets Detail.Master

public class Master
{
    public string ID { get; set; }

    public IEnumerable<Detail> Details
    {
        get => details;
        set
        {
            foreach(var detail in value)
            {
                detail.Master = this;
            }
            this.details = value;
        }
    }

    private IEnumerable<Detail> details { get; set; }
}

Usage:

var master = new Master
{
    Details = new List <Detail>
    {
        new Detail {}
    }
};


Console.WriteLine(
    master.Details.All(detail => detail.Master == master)
);