简体   繁体   中英

C# automapper check all enum values are in map

I am mapping from my domain model to a databaseDto. Both hold an enum representing a range of states.

Is there any way of checking all the values in one enum can be mapped with automapper once the mapper has been built from its configuration (or maybe in a unit-test)

You can use example code below;

    public class Program
    {
        public static void Main(string[] args)
        {
            CreateMaps();

            Lender src = new Lender()
            {
                Id = 1,
                Name = "Bob",
                ClaimTypes = ClaimType.A | ClaimType.C
            };

            LenderServiceModel dest = Mapper.Map<LenderServiceModel>(src);

            Console.WriteLine("{0}: {1}", dest.Id, dest.Name);

            foreach(var claimType in dest.ClaimTypes)
            {
                Console.WriteLine(claimType);
            }
        }

        private static void CreateMaps()
        {
            Mapper.CreateMap<Lender, LenderServiceModel>()
                .ForMember(dest => dest.ClaimTypes, opts => opts.MapFrom(src =>
                    src.ClaimTypes.ToString().Split(new string[]{", "}, StringSplitOptions.None).ToList()));
        }
    }

    [Flags]
    public enum ClaimType : int
    {
        A = 1,
        B = 2,
        C = 4
    }

    public class Lender
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public ClaimType ClaimTypes { get; set; }
    }

    public class LenderServiceModel 
    {
        public int Id { get; set; }

        public string Name { get; set; }

        public List<string> ClaimTypes { get; set; }
    }

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