Last active
February 26, 2021 13:38
-
-
Save rgilmutdinov/0b849e16ef6f9eac8c0d3c7998fc4fec to your computer and use it in GitHub Desktop.
Self model projection does not take into account `Ignore` option for inner collections
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using System; | |
| using AutoMapper; | |
| using AutoMapper.QueryableExtensions; | |
| using System.Collections.Generic; | |
| using System.Linq; | |
| public class ClassA | |
| { | |
| public string Name { get; set; } | |
| public string Type { get; set; } | |
| } | |
| public class ClassB | |
| { | |
| public string Name { get; set; } | |
| public List<ClassA> Classes { get; set; } | |
| } | |
| public class Program | |
| { | |
| public static void Main() | |
| { | |
| var configuration = new MapperConfiguration(cfg => | |
| { | |
| cfg.CreateMap<ClassA, ClassA>() | |
| .ForMember(dest => dest.Name, opts => opts.MapFrom(src => src.Name)) | |
| .ForAllOtherMembers(opts => opts.Ignore()); | |
| cfg.CreateMap<ClassB, ClassB>() | |
| .ForMember(dest => dest.Name, opts => opts.MapFrom(src => src.Name)) | |
| .ForMember(dest => dest.Classes, opts => opts.MapFrom(src => src.Classes)) | |
| .ForAllOtherMembers(opts => opts.Ignore()); | |
| }); | |
| List<ClassB> source = new List<ClassB>(); | |
| source.Add(new ClassB() { Name = "b1", Classes = new List<ClassA>() { new ClassA() { Name = "a1", Type = "type" }, new ClassA() { Name = "a2", Type = "type" }, new ClassA() { Name = "a3", Type = "type" } } }); | |
| var mapper = configuration.CreateMapper(); | |
| var result = source.AsQueryable().ProjectTo<ClassB>(mapper.ConfigurationProvider); | |
| //var expression = result.Expression; | |
| ClassB target = result.First(); | |
| foreach (ClassA classA in target.Classes) | |
| { | |
| if (!string.IsNullOrEmpty(classA.Type)) | |
| { | |
| // we shouldn't get here | |
| Console.WriteLine(classA.Name + " " + classA.Type); | |
| } | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment