忽略Automapper中从目标到源的属性?

时间:2017-06-25 20:08:48

标签: c# automapper

映射配置文件:

Mapper.CreateMap<Customer, CustomerDto>();
        Mapper.CreateMap<CustomerDto, Customer>();
        Mapper.CreateMap<Movie, MoviesDto>();
        Mapper.CreateMap<MoviesDto, Movie>(MemberList.Source);

Movie上课:

namespace Demo3.Models
{
    public class Movie
    {
        public int Id { get; set; }

        [Required(ErrorMessage = "Please Enter Customer Name")]
        [StringLength(255)]
        public string Name { get; set; }

        public Genre Genre { get; set; }

        [Required]
        public byte GenreId { get; set; }

        public DateTime DateAdded { get; set; }
        [Display(Name = "Release Date")]
        public DateTime ReleaseDate { get; set; }

        [Display(Name = "Number In Stock")]
        [Range(1, 20)]
        public byte NumberInStock
        {
            get; set;
        }
    }
}

MoviesDto上课:

namespace Demo3.Dtos
{
    public class MoviesDto
    {
        public int Id { get; set; }

        [Required]
        [StringLength(255)]
        public string Name { get; set; }

        [Required]
        public byte GenreId { get; set; }

        public DateTime ReleaseDate { get; set; }

        //public Genre Genre { get; set; }
        [Range(1, 20)]
        public byte NumberInStock
        {
            get; set;
        }
    }
}

例外:

  

EntityFramework.dll中出现'System.InvalidOperationException'类型的异常,但未在用户代码中处理

enter image description here

enter image description here

我需要在保存时忽略Genre属性。

1 个答案:

答案 0 :(得分:0)

当定义单个属性映射(由于它们通过具有相同的名称而自动映射而没有得到)时,您必须指定一个ignore指令,如下所示:

Mapper.CreateMap<MoviesDto, Movie>()
      .ForMember(d => d.Genre, o => o.Ignore());