简体   繁体   中英

Using Automapper with Flags Enum

I'm trying to figure out how to use AutoMapper with the following scenario :-

I have the following Entity Model :-

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

        //Other properties kepy out for brevity.
    }

And Here is The Following Service Model :-

public class LenderServiceModel 
    {
        [Editable(false)]
        public int Id { get; set; }

        [Editable(false)]
        public string Name { get; set; }

        [Editable(false)]
        public List<string> ClaimTypes { get; set; }
    }

In the case of the Entity model, the ClaimType property is a Flags Enum :-

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

    }

I want to be able to map from the Entity Model, to the Service Model. I need to map the ClaimType to List on the Service Model, but i have had no luck.

I'm new to AutoMapper, any help would be apreciated.

First you need to get hold of a string list representation of your enum flags, this can be done with this statement

var t = Enum.GetValues(typeof(ClaimType)).Cast<ClaimType>().Where(r => (claimType & r) == r).Select(r => r.ToString()).ToList();

For specific mappings with AutoMapper you need to specify it while setting it up. So for this that will be following code: so we map ClaimTypes field from source to destination using the list conversion...

AutoMapper.Mapper.CreateMap<LegacyEntity, LenderServiceModel >()
    .ForMember(dest => dest.ClaimTypes,
               opts => opts.MapFrom(Enum.GetValues(typeof(ClaimType)).Cast<ClaimType>().Where(r => (src.ClaimTypes & r) == r).Select(r => r.ToString()).ToList());

You need to create a property mapping for ClaimTypes, which converts each flags value to a string. There are a few ways to do this. Take a look at this answer for some ideas.

Here's how you can set it up in AutoMapper (using a quick and dirty method of just ToString() ing the enum then splitting the string):

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

You can see a working .NETFiddle here

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