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

不羁岁月 提交于 2019-12-11 08:25:25

问题


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.


回答1:


"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;
    }
}


来源:https://stackoverflow.com/questions/9382409/when-mapping-automapper-need-to-convert-a-type-enum-to-a-bool

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!