-2

I'm trying to add a list to the dto, in order for the dto top be mapped to an actual context class using AutoMapper, for some reason when i add the List to the dto's attribute and map it, upon debugging it throws an error with the exception:

The object reference is set to null.

DevDto.cs: (This is the Dto):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using Auth.Models;
namespace Auth.Dtos
{
    public class DevDto
    {
        public byte Id { get; set; }
        [Required(ErrorMessage = "Name is required")]
        public string Name { get; set; }
        public string Email { get; set; }
        public ICollection<Tags> Tags { get; set; }
    }
}

DevController (Class where the dto is trying to map to the Developer class):

  public IHttpActionResult SaveDev(DevDto dev)
    {

        List<Tags> tags = new List<Tags>();

            foreach(var ss in dev)
        {
            tags.Add(_context.Tag.Single(m => m.Id == ss.TagId));
        } 
            foreach(var tt in tags)
        {
            dev.Tags.Add(tt);
        }
            var de = Mapper.Map<DevDto, Developers>(dev);
            _context.Developer.Add(de);

Note: The Developer and Tag class have a one to many relationship respectively as the Developer class has Tag defined as:

public Tags Tag{get; set;}

Similarly the Tag class has Developer defined as:

public ICollection<Developer> Developer {get; set;}
Andrew
  • 18,946
  • 6
  • 54
  • 66
Shad
  • 23
  • 1
  • 8

1 Answers1

1

The error is occuring because the property Tags of class DevDto is not instantiated when you are adding items to it, hence the error. Read more about the exception here - What is a NullReferenceException, and how do I fix it?

What you can do as a null-check practice is to instantiate the class containing properties of ICollection types as follows:

    public class DevDto
    {
        //Null-exception check
        public DevDto()
        {
            Tags = new List<Tags>();
        }


        public byte Id { get; set; }
        [Required(ErrorMessage = "Name is required")]
        public string Name { get; set; }
        public string Email { get; set; }
        public ICollection<Tags> Tags { get; set; }
    }
iSahilSharma
  • 1,629
  • 1
  • 11
  • 30
  • If there is already an answer to this question you should vote to close as a duplicate. If there is anything new that you are adding then consider answering in the duplicate. – Enigmativity Jan 29 '19 at 08:16
  • I have answered before it was marked duplicate. However, the answer is related to fix the exception occurred, not to show what is the exception. – iSahilSharma Jan 29 '19 at 08:19
  • But you referenced the duplicate in your answer... – Enigmativity Jan 29 '19 at 09:12