我有一个领域模型,它包含以下属性:
public class Profile
{
public DateTime birthDate { get; set; }
public List<Language> languages { get; set; }
}
其中Language表示此处定义的枚举:
public enum Language
{
English,
French,
Spannish
}
我想基于我的域模型中存储的语言值自动填充以下两个属性:
public Dictionary <int, String> languages_list { get; set; }
public List<string> languages_known { get; set; }
问题是:是否可以使用automapper完成,如果是这样,我该怎么办?
答案 0 :(得分:0)
好的,使用您提供的详细信息,这就是我的想法。
<强>类强>
public class SOProfile
{
public DateTime birthDate { get; set; }
public List<Language> languages { get; set; }
}
public class WhatAmI
{
public Dictionary<int, String> languages_list { get; set; }
public List<string> languages_known { get; set; }
}
请注意,Profile
已重命名为SOProfile
,以避免与AutoMapper
冲突
AutoMapper配置
public class MyProfile : Profile
{
public override string ProfileName
{
get
{
return "MyProfile";
}
}
protected override void Configure()
{
Mapper.CreateMap<SOProfile, WhatAmI>()
.ForMember(dest => dest.languages_list,
opt => opt.MapFrom(
src => src.languages
.Select((x,i) => new { Item = x, Index = i})
.ToDictionary(x => x.Index,
x => x.Item.ToString())))
.ForMember(dest => dest.languages_known,
opt => opt.MapFrom(
src => src.languages
.Select(x => x.ToString()).ToList()));
}
}
单元测试
[TestFixture]
public class MappingTests
{
[Test]
public void AutoMapper_Configuration_IsValid()
{
Mapper.Initialize(m => m.AddProfile<MyProfile>());
Mapper.AssertConfigurationIsValid();
}
[Test]
public void AutoMapper_Mapping_IsValid()
{
Mapper.Initialize(m => m.AddProfile<MyProfile>());
Mapper.AssertConfigurationIsValid();
var profile = new SOProfile
{
birthDate = new DateTime(2012, 01, 01),
languages = new List<Language>
{
Language.English,
Language.French,
Language.English,
Language.French
}
};
var rc = Mapper.Map<SOProfile, WhatAmI>(profile);
Assert.That(rc, Is.Not.Null);
Assert.That(rc.languages_known, Is.Not.Null);
Assert.That(rc.languages_known.Count, Is.EqualTo(4));
Assert.That(rc.languages_known.Count(x => x == "English"),
Is.EqualTo(2));
Assert.That(rc.languages_known.Count(x => x == "French"),
Is.EqualTo(2));
Assert.That(rc.languages_known.Count(x => x == "Spanish"),
Is.EqualTo(0));
Assert.That(rc.languages_list, Is.Not.Null);
Assert.That(rc.languages_list.Count, Is.EqualTo(4));
Assert.That(rc.languages_list.First(x => x.Key == 0).Value,
Is.EqualTo("English"));
Assert.That(rc.languages_list.First(x => x.Key == 1).Value,
Is.EqualTo("French"));
Assert.That(rc.languages_list.First(x => x.Key == 2).Value,
Is.EqualTo("English"));
Assert.That(rc.languages_list.First(x => x.Key == 3).Value,
Is.EqualTo("French"));
}
}