jeudi 7 octobre 2021

How to created builder for nested objects

I am looking for a way to create a builder that can create nested objects.

I have already read this topic: Builder pattern with nested objects but that approach is modyfing model/entities which I'd like to avoid.

I have few models: Advertisment has an Owner, Owner has an Address and Address has a Contact entity.

public class Advertisment
{
    public string AdvertismentId { get; set; }
    public Owner Owner { get; set; }
}
public class Owner
{
    public string Name { get; set; }
    public Address Address { get; set; }
}
public class Address
{
    public string Street { get; set; }
    public Contact Contact { get; set; }
}
public class Contact
{
    public string PhoneNo { get; set; }
}

I would like to chain methods like this (or something similar):

        var ad = new AdBuilder()
                    .WithId("123")
                    .WithOwner(x =>
                        x.WithName("NameOfOwner")
                        x.WithAddress(x => x.WithStreet("SomeStreet"))
                        .WithContact(y => y.WithPhoneNo("123-345-789"))));

I prepared the code here: https://rextester.com/TRN19779

I don't want to modify models because they are generated from JSON Schema and I keep them in a separte class library. I am going to use above builder to map one object to another. I am preparing an object to send to 3rd party consumer.

Would be someone so nice and help a bit?

Aucun commentaire:

Enregistrer un commentaire