Automapper Map(十进制,货币)到Money

时间:2013-09-25 23:42:32

标签: c# .net mapping automapper currency

我有:

public class Money
{
   public decimal Amount {get;set;}
   public CurrencyCodeType CurrencyCode {get;set;} //this is an enum
}

public class Person //Domain class
{
   public Money Salary {get;set;}
}

public class PersonDb  //Generated from Db
{
   public decimal SalaryAmount {get;set;}
   public string  SalaryCurrencyCode {get;set;}
}

钱从这里接近:

http://martinfowler.com/eaaCatalog/embeddedValue.html

http://martinfowler.com/eaaCatalog/money.html

我有Autmapper的下一个配置:

public class MoneyProfile : Profile
{
    protected override void Configure()
    {
        Mapper.CreateMap<decimal, Money>().ConvertUsing<MoneyToDecimalTypeConverter>();
        Mapper.CreateMap<Money, decimal>().ConvertUsing<DecimalToMoneyTypeConverter>();
    }

    public class DecimalToMoneyTypeConverter : ITypeConverter<Money, decimal>
    {
        public decimal Convert(ResolutionContext context)
        {
            return ((Money)context.SourceValue).Amount;
        }
    }

    public class MoneyToDecimalTypeConverter : ITypeConverter<decimal, Money>
    {
        public Money Convert(ResolutionContext context)
        {
            return new Money((decimal)context.SourceValue);
        }
    }
}

public class PersonProfile : Profile
{
    protected override void Configure()
    {
        var mapDomainToDb = Mapper.CreateMap<Person, PersonDb>();
        mapDomainToDb.ForMember(db => db.SalaryAmount, options => options.MapFrom(domain => domain.Salary.Amount));
        mapDomainToDb.ForMember(db => db.SalaryCurrencyCode, options => options.MapFrom(domain => domain.Salary.CurrencyCode));

        var mapDbToDomain = Mapper.CreateMap<PersonDb, Person>();
        // ?????
    }
}

我不知道如何将Db映射到域,如何从十进制和字符串创建Money对象。请任何人都可以帮助我,我第一次使用自动播放器。

1 个答案:

答案 0 :(得分:1)

你应该能够做到这样的事情:

Mapper.CreateMap<PersonDb, Person>()
    .AfterMap((src, dest) => {
        dest.Salary = new Money();
        dest.Salary.Amount = src.SalaryAmount;
        dest.Salary.CurrencyCode = enum.Parse(typeof(CurrencyCodeType), src.SalaryCurrencyCode);
    });
编辑:对不起,我的订单错了。 Editted。