简体   繁体   English

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

[英]Ignore property in Automapper from destination to source?

Mapping profile: 映射配置文件:

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

Movie class: 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 class: 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;
        }
    }
}

Exception: 例外:

An exception of type 'System.InvalidOperationException' occurred in EntityFramework.dll but was not handled in user code EntityFramework.dll中发生类型'System.InvalidOperationException'的异常,但未在用户代码中处理

在此处输入图片说明

and

在此处输入图片说明

My need is to ignore the Genre property while saving. 我需要在保存时忽略Genre属性。

When defining the individual property mappings (which you got away without because they get mapped automagically, by having the same name), you have to specify an ignore instruction, like so: 在定义单个属性映射时(您之所以会幸免,因为它们通过使用相同的名称自动映射),您必须指定一条忽略指令,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM