当映射(automapper)需要一个枚举类型转换为布尔 [英] When mapping (automapper) need to convert a type enum to a bool

查看:1913
本文介绍了当映射(automapper)需要一个枚举类型转换为布尔的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下的模式

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

我有以下的视图模式

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

有关YesNoEnumViewModel我用下面的枚举类型:

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
}

在我的code,我需要我的视图模型映射到我的模型。所以,我试试这个:

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);
        ...
    }

和试图映射时,我得到了一个错误。该错误是从枚举类型YesNoEnumViewModel转换为bool(在我的模型属性为BOOL类型)。

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).

下面是我的CreateMap:

Here is my CreateMap:

Mapper.CreateMap<FooViewModel, Foo>();

也许我需要在CreateMap指定为成员的的IsValid我FooViewModel一些特别的东西必须做到将其转换为我的模型的布尔?

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?

感谢您的帮助。

推荐答案

也许我需要在CreateMap指定为我FooViewModel一些特殊成员的IsValid必须完成将其转换为我的模型的布尔?

"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?"

没错,你需要创建一个知道如何解决YesNoEnumViewModel布尔自定义解析:

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

这篇关于当映射(automapper)需要一个枚举类型转换为布尔的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆