开发者

Automapper - How to reuse objects instead of creating new ones (this objects are in a list)

I got the following problem: I got a Entity (from EF Code First) that looks like this.

 public class Movie {
 public ICollection<AudioQuality> AudioQualities  {get;set;}
}

public class AudioQuality {
public Guid Id{get;set;}
public int Channels{get;set;}
}

//Automapper Init:
Mapper.CreateMap<Movie, MovieDto>();
        Mapper.CreateMap<MovieDto, Movie>()开发者_运维技巧.ForMember(dest => dest.AudioQualities,opt => opt.UseDestinationValue());


        Mapper.CreateMap<VideoQuality, VideoQualityDto>();
        Mapper.CreateMap<AudioQuality, AudioQaulityDto>();

        Mapper.CreateMap<VideoQualityDto, VideoQuality>();
        Mapper.CreateMap<AudioQaulityDto, AudioQuality>()
            .ForMember(dest => dest.Movies, opt => opt.Ignore());

And I also got a DTO that looks similar!

I map from the DTO to the Entity like so:

//Get Movie from DB and than update it with the dto values
Movie movieFromDb = GetMoviesWithAllChilds().Single(mov => mov.Id == movieDto.Id);

//use update the entity from db with dto
Mapper.Map(movieDto, movieFromDb);

Now the problem is, that Automapper creates a new AudioQuality-Object for each item in AudioQualities.

But I want that he just copies the values from the AudioQuality-Objects from the DTO to the Entities instead of creating new Objects with the values from the DTO.

Is there a way to do that??

FYI: UseDestinationValue works on the collection (so the collection is not copied).

br rene_r


Get your entity from the context and pass it in to the Mapper function as the second parameter. The updates will eb applied from the source to the destination.

mapper.Map<SourceType, DestType>(source, dest);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜