简体   繁体   中英

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:

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:

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

在此处输入图片说明

and

在此处输入图片说明

My need is to ignore the Genre property while saving.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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