简体   繁体   English

自动映射将标记枚举从ViewModel映射到域模型

[英]Automapper mapping Flags Enum from ViewModel to Domain model

While trying to translate between my ViewModel and my domain model using AutoMapper I noticed that it does not play well with Enums marked the the Flags attribute. 在尝试使用AutoMapper在我的ViewModel和我的域模型之间进行转换时,我注意到它与标记Flags属性的Enums不兼容。

Here is a quick mockup of the classes: 这是类的快速模型:

ViewModel: 视图模型:

public class TestViewModel
{
    // array of individual Enum values
    public TestEnum[] TestEnum { get; set; } 
}

Domain Model: 领域模型:

public class TestModel
{
    // single Enum marked with flags attribute
    public TestEnum TestEnum { get; set; }
}

Enum: 枚举:

[Flags]
public enum TestEnum
{
    Test1,
    Test2,
    Test3,
    Test4
}

This is what I am trying to do. 这就是我想要做的。 I guess I need a Custom resolver of some sort in my Automapper config because it throws an exception when I do Mapper.Map(). 我想我需要在我的Automapper配置中使用某种自定义解析器,因为它在我执行Mapper.Map()时会抛出异常。

My question: How would I accomplish this? 我的问题:我将如何做到这一点?

Bonus question: Is this best practice for handling Flags Enums / Bitmasks in Viewmodel -> Domain models (in a MVVM respect)? 额外问题:这是处理Viewmodel中的Flags Enums / Bitmasks的最佳实践 - >域模型(在MVVM方面)吗? If not, what practice would you suggest (using AutoMapper or otherwise)? 如果没有,你会建议采用什么做法(使用AutoMapper或其他方式)?

When mapping to the view model, you can try to use Enum.GetValues() and LINQ to get a list of enum values. 映射到视图模型时,您可以尝试使用Enum.GetValues()和LINQ来获取枚举值列表。 To map back to the model, try using Aggregate() ... 要映射回模型,请尝试使用Aggregate() ...

Mapper.CreateMap<TestModel, TestViewModel>()
    .ForMember(v => v.TestEnum, 
        x => x.MapFrom(m => Enum.GetValues(typeof(TestEnum))
                            .Cast<TestEnum>()
                            .Where(e => (e & m) > 0)
                            .ToList()))
    .ReverseMap()
    .ForMember(m => m.TestEnum,
        x => x.MapFrom(v => v.Aggregate((i, j) => i | j));

As for whether this is the best approach, it really depends on how the view model is being used. 至于这是否是最好的方法,它实际上取决于视图模型的使用方式。 Currently, the view model doesn't contain flags that aren't set; 目前,视图模型不包含未设置的标志; do you need them for rendering the view? 你需要它们来渲染视图吗?

I'd skip AutoMapper and go the model binding route. 我将跳过AutoMapper并进入模型绑定路径。 If you're using ASP.NET MVC, you can hook directly into model binding so that all values are combined into one. 如果您正在使用ASP.NET MVC,则可以直接挂钩到模型绑定,以便将所有值合并为一个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM