Base solution for your next web application
Open Closed

async insert parent and children #3628


User avatar
0
fguo created

I am trying to provide an API to insert a parent object with children objects. For testing, I modified a little from the phonebook example, but it always throws out System.NullReferenceException: Object reference not set to an instance of an object.

Here is my code:

    public async Task<PhoneInPersonListDto> AddPhone(AddPhoneInput input)
    {
        var person = new Person();
        person.Name = "x";
        person.Surname = "y";

        var phone = ObjectMapper.Map<Phone>(input);
        person.Phones.Add(phone);

        var personId = await _personRepository.InsertAndGetIdAsync(person);

        return ObjectMapper.Map<PhoneInPersonListDto>(phone);
    }

Can you advise what I missed?

Thanks,


3 Answer(s)
  • User Avatar
    0
    ismcagdas created
    Support Team

    Hi,

    You need to create an empty list for Phones of person before adding an item to it. You can do it in the constructor of your Person entity.

    Thanks.

  • User Avatar
    0
    fguo created

    Got it. Because the Phone is defined in Person as virtual ICollection<Phone>, it is not initiated along with "new Person()". I modified my code as following (adding 2 lines with comment):

    public async Task<PhoneInPersonListDto> AddPhone(AddPhoneInput input) { var person = new Person(); person.Phones = new List<Phone>(); // concrete ICollection<Phone> person.Name = "x"; person.Surname = "y";

    var phone = ObjectMapper.Map<Phone>(input); person.Phones.Add(phone);

    var personId = await _personRepository.InsertAndGetIdAsync(person); var phoneId = phone.Id; // Cannot get this if using InsertAsync(person).

    return ObjectMapper.Map<PhoneInPersonListDto>(phone); }

    It works as expected. Thank you! :)

    BTW, do you think the "new List<T>(); " is the best way to initiate ICollection<T>?

  • User Avatar
    0
    ismcagdas created
    Support Team

    Hi,

    BTW, do you think the "new List<T>(); " is the best way to initiate ICollection<T>?

    I personally use it like that but I don't know if it is the best way or not :)