开发者

Automapper: Is there a built-in way to map a condition from the source object to a boolean on the target?

I just开发者_StackOverflow threw together a custom AutoMapper ValueResolver to try to map a condition from my domain object to a boolean property on an MVC view model, and it's so simple that I have a feeling there has to be a built-in way to do what I'm trying to do without a custom resolver.

The logic that I'm trying to implement is that if "MyDomainObject.MyStatus" is equal to "StatusCode.Inactive" then the value mapped to the view model ("MyViewModel.CanRemove") should be false.

Here's my (simplified) example:

// Domain Object:
public class MyDomainObject
{
    public int Id{get;set;}
    public StatusCode MyStatus{get;set;}
} 

public enum StatusCode
{
    Active,
    Inactive 
 }

// View Model:
public class MyViewModel
{
    public int Id{get;set;}
    public bool CanRemove{get;set;}
}

// My custom resolver
public class BooleanValueResolver<T> : ValueResolver<T,bool>
{
    private readonly Func<T, bool> _condition;

    public BooleanValueResolver(Func<T,bool> condition)
    {
        _condition = condition;
    }

    protected override bool ResolveCore(T source)
    {
        return _condition(source);
    }
}

// My AutoMapper mapping:

public class MyMappingProfile : Profile
{
    protected override void Configure()
    {
        Mapper.CreateMap<MyDomainObject, MyViewModel>()
            .ForMember(viewModel => viewModel.CanRemove,
                opt => opt.ResolveUsing(new BooleanValueResolver<MyDomainObject>(domainObject => !domainObject.MyStatus.Equals(StatusCode.Inactive))));
    }
}

Does anyone know if it's possible to achieve this behavior without using my custom ValueResolver?


I think this would be the equivalent (using Automapper's built-in MapFrom):

.ForMember(d => d.CanRemove, o => o.MapFrom(s => s.MyStatus.Equals(StatusCode.Inactive))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜