tags:

views:

42

answers:

1

I just 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?

+1  A: 

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))
Patrick Steele
Yep, that works, Thanks Patrick!
jrnail23

related questions