对象引用未设置为对象的实例(将列表映射到Automapper)

时间:2019-01-29 05:41:56

标签: c# entity-framework linq

我正尝试将列表添加到dto,以便使用AutoMapper将dto顶部映射到实际的上下文类,出于某种原因,当我在调试时将列表添加到dto的属性并映射它时引发错误,但出现以下异常:

The object reference is set to null.

DevDto.cs :(这是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(dto试图映射到Developer类的类):

  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);

注意:Developer和Tag类分别具有一对多的关系,因为Developer类将Tag定义为:

public Tags Tag{get; set;}

类似地,Tag类将Developer定义为:

public ICollection<Developer> Developer {get; set;}

1 个答案:

答案 0 :(得分:0)

发生错误是因为在向其添加项目时未实例化DevDto类的属性Tags,因此发生错误。在此处详细了解异常-What is a NullReferenceException, and how do I fix it?

您可以通过null-check的做法来实例化包含ICollection types属性的类,如下所示:

    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; }
    }