Bronzato
Bronzato

Reputation: 9342

When mapping (automapper) need to convert a type enum to a bool

I have the following model:

public class Foo
{
    [Key]
    public int      FooID { get; set; }
    public string   Description { get; set; }
    public bool     IsValid{ get; set; }
}

I have the following view model:

public class FooViewModel
{
    public int FooId { get; set; }
    public string Description { get; set; }
    public YesNoEnumViewModel IsValid{ get; set; }
}

For the type YesNoEnumViewModel I used the following enum:

public enum YesNoEnumViewModel
{
    [Display(Name = "Yes", ResourceType = typeof(UserResource))]
    Yes = 1,
    [Display(Name = "No", ResourceType = typeof(UserResource))]
    No = 2
}

In my code I need to map my viewModel into my model. So I try this:

    [HttpPost]
    public ActionResult AddedNew(FooViewModel viewModel)
    {
        if (!ModelState.IsValid)
            return PartialView("AddedNew", viewModel);

        var foo = Mapper.Map<FooViewModel, FooModel>(viewModel);
        ...
    }

And I got an error when trying to map. The error is on the converting from the enum type YesNoEnumViewModel to bool (the property in my model is of type bool).

Here is my CreateMap:

Mapper.CreateMap<FooViewModel, Foo>();

Maybe I need to specify in the CreateMap that for member IsValid of my FooViewModel something special must be done to convert it to a bool of my model?

Thanks for your help.

Upvotes: 1

Views: 3982

Answers (1)

Bojin Li
Bojin Li

Reputation: 5799

"Maybe I need to specify in the CreateMap that for member IsValid of my FooViewModel something special must be done to convert it to a bool of my model?"

Exactly, you need to create a custom Resolver that knows how to resolve YesNoEnumViewModel to Boolean:

Mapper.CreateMap<FooViewModel, Foo>().
     ForMember(dest => dest.IsValid, opt => opt.ResolveUsing<EnumResolver>());

internal class EnumResolver : ValueResolver<FooViewModel, bool>
{
    protected override bool ResolveCore(FooViewModel vm)
    {
        return vm.IsValid == YesNoEnumViewModel.Yes;
    }
}

Upvotes: 3

Related Questions