Search code examples
c#modelviewmodelasp.net-mvc-viewmodeldomain-model

Null reference issue occurs when converting from Domain model to View model


The below code throws null reference exception when there is no data to be returned from the stored procedure. Method executes successfully if data is present.

Am I doing anything wrong with the below code? Do I need to create an object from the model?

public PersonVM GetStaff()
{
    PersonDM personDM = _Repo.GetStaff();
    PersonVM personVM = PersonVM.ToViewModel(personDM);
    return personVM;
}

public class PersonDM
{
    public int RoleID { get; set; }
    public string Name { get; set; }
}

public class PersonVM
{
    public int RoleID { get; set; }
    public string Name { get; set; }

    public static PersonVM ToViewModel(PersonDM model)
    {
        return new PersonVM
        {
            RoleID = model.RoleID,
            Name = model.Name
        };
    }

    public PersonDM ToEntityModel()
    {
        return new PersonDM
        {
            RoleID=this.=RoleID,
            Name = this.Name,
        }
    }
}

When there is no data to be returned from the SP personDM becomes NULL. I need it to be filled with null values without returning NULL. Is it possible to achieve?

Image

I did the same thing with a method which is returning a List<PersonVM> with the below code. It fills the VM with NULL values if there is no data present. How can apply the below code to a method which is returning the type PersonVM

public List<PersonVM> GetPartyByPartyRelationship(int partyRoleId, int partyRelationshipTypeId)
    {
        List<PersonDM> personDMList = _partyManagerRepo.GetPartyByPartyRelationship(partyRoleId, partyRelationshipTypeId);
        List<PersonVM> personVMList = new List<PersonVM>();
        foreach (PersonDM personDM in personDMList)
        {
            personVMList.Add(PersonVM.ToViewModel(personDM));
        }

        return personVMList;
    }

Solution

  • Assuming that _Repo.GetStaff() is returning null and therefore personDM is null, it should not be a surprise that a NullReferenceException is being thrown as you're trying to access object properties within ToViewModel() on a null reference.

    Add a null check, either in GetStaff() or ToViewModel() and handle appropriately. Based on your update, you say you want to return a viewmodel with null properties, which you can do with the null check:

    public static PersonVM ToViewModel(PersonDM model)
    {
        if (model == null)
            return new PersonVM();
    
        return new PersonVM
        {
            RoleID = model.RoleID,
            Name = model.Name
        };
    }
    

    Update - Or, change your ToViewModel() method to utilise the null-progagating operator:

    public static PersonVM ToViewModel(PersonDM model)
    {
        return new PersonVM
        {
            RoleID = model?.RoleID,
            Name = model?.Name
        };
    }