Type Adapter Configuration

Test Classes

public class Address
{
    public int Id { get; set; }
    public string Street { get; set; }
    public string PostalCode { get; set; }
    public string City { get; set; }
    public string Country { get; set; }
}

public class AddressDTO
{
    public int Id { get; set; }
    public string PostalCode { get; set; }
    public string FullAddress { get; set; }
}


Configure

//TypeAdapterConfiguration.cs
public static class TypeAdapterConfiguration
{
    public static void Initialize()
    {
        TypeAdapterConfig<Address, AddressDTO>
          .NewConfig()
          .IgnoreMember(dest => dest.PostalCode)
          .MapFrom(dest => dest.FullAddress, 
                   src => string.Format("{0}, {1}, {2}", src.Street, src.City, src.Country)
          );
    }
}

//Global.asax
protected void Application_Start()
{
    TypeAdapterConfiguration.Initialize();
}


Test Data

public Address GetAddress()
{
    Address address = new Address() { 
        Id = 1, 
        Street = "Istiklal Cad.",
        PostalCode = "34000",
        City = "Istanbul", 
        Country = "Turkey"
    };

    return address;
}


Map

var addressDto = TypeAdapter.Adapt<Address, AddressDTO>(GetAddress());

//result : 
// addressDto.Id == 1
// addressDto.PostalCode == null //Ignored
// addressDto.FullAddress == "Istiklal Cad., Istanbul, Turkey"

Last edited Mar 28, 2014 at 11:16 AM by timucinkivanc, version 3