How to map int to boolean

I am using AutoMapper 5.2. I currently have a display operator that looks like this:

 CreateMap<JeffreysOnline.Data.Customer, JeffreysOnline.Entities.Customer>()
                .ForMember(s => s.CustomerWant, t => t.Ignore());

      

The table "Customer" and "Customer" have a field "BadChecks". In the database, this is int. I recently changed the type to bool in my entity. AutoMapper is now giving me the following error:

Unable to create a map expression from Customer.BadChecks (System.Int16) to Customer.BadChecks (System.Boolean) Mapping types: Customer -> Customer JeffreysOnline.Data.Customer -> JeffreysOnline.Entities.Customer Type Map configuration: Customer -> Customer JeffreysOnline.Data.Customer -> JeffreysOnline.Entities.Customer Property: BadChecks

      

It seems AutoMapper doesn't know how to map from int to boolean. Can AutoMapper help me with this?

It might be helpful to know that in my DAL I am using ProjectTo () to pass the IQueryable to another method trying to access the data and so the mapping happens (an error is generated). My DAL code looks like this:

return entityList.OrderBy(row => row.LastName).ProjectTo<Entities.Customer>();

      

+3


source to share


2 answers


Automapper 6.0.2 - Works without any ForMember ... null, 0 = false, values> = 1 are mapped to true.

In Automapper 6.0.2 - in a different way:

    class nnnProfile : Profile
    {
        CreateMap<src, dst>()
            .ForMember(d => d.Decision, opt => opt.ResolveUsing<CustomBoolResolver>());    
    }

      

Resolver:



public class CustomBoolResolver : IValueResolver<src, dst, bool>
{
    public bool Resolve(src source, dst destination, bool destMember,
        ResolutionContext context)
    {
        return source.Decision == 1;
    }
}

      

but this is for Destination so there isn't much flexibility.

According to this page: http://taswar.zeytinsoft.com/automapper-mapping-objects-part-5-of-7-customresolver/

In the past, you could write your own recognizer with a single source and target type.

+5


source


I don't think I know how to map from int to boolean.

If you figure out how this should happen, you need to create a mapping from int to boolean .:

CreateMap<int, bool>().ProjectUsing(src => src != 0);

      



Fully guessing. But since you are using ProjectTo you need to use ProjectUsing for the expression to do it anyway before the DAL.

Be aware that when using ProjectUsing, AutoMapper does not actually do the mapping. It creates a LINQ "Select" expression, which it passes down to your query provider (EF perhaps?). Thus, you need to make sure that whatever you use in your predictor expression EF can support translation eventually to SQL.

+2


source







All Articles