public class Member { public string MemberId {get;set;} public string MemberType {get;set;} public string Name {get;set;} }
会员类型可以是“人”或“公司”。
还有两个这样的目的地类
public class PersonMember { public int PersonMemberId {get;set;} public string Name {get;set;} } public class CompanyMember { public int CompanyMemberId {get;set;} public string Name {get;set;} }
var config = new MapperConfiguration(cfg => { cfg.CreateMap() .ForMember(dest => dest.baz, opt => opt.Condition(src => (src.baz >= 0))); });
我的目标是这样的 –
cfg.CreateMap() .ForMember(dest => PersonMember.PersonMemberId, opt => if the source.MemberType == "Person" perform mapping from MemberId, otherwise do nothing); cfg.CreateMap() .ForMember(dest => CompanyMember.CompanyMemberId, opt => if the source.MemberType == "Company" perform mapping from MemberId, otherwise do nothing);
using System; using AutoMapper; namespace AutoMapOneToMulti { class Program { static void Main(string[] args) { RegisterMaps(); var s = new Source { X = 1, Y = 2 }; Console.WriteLine(s); Console.WriteLine(Mapper.Map
对于低于5的版本,您可以尝试这样做:
using System; using AutoMapper; namespace AutoMapOneToMulti { class Program { static void Main(string[] args) { RegisterMaps(); var s = new Source { X = 1, Y = 2 }; Console.WriteLine(s); Console.WriteLine(Mapper.Map(s)); Console.WriteLine(Mapper.Map(s)); Console.ReadLine(); } static void RegisterMaps() { Mapper.Initialize(cfg => cfg.AddProfile()); } } public class GeneralProfile : Profile { protected override void Configure() { CreateMap(); CreateMap(); } } public class Source { public int X { get; set; } public int Y { get; set; } public override string ToString() { return string.Format("Source = X : {0}, Y : {1}", X, Y); } } public class Destination1 { public int X { get; set; } public int Y { get; set; } public override string ToString() { return string.Format("Destination1 = X : {0}, Y : {1}", X, Y); } } public class Destination2 { public int X { get; set; } public int Y { get; set; } public override string ToString() { return string.Format("Destination2 = X : {0}, Y : {1}", X, Y); } } }
如果您想要动态function,请使用此扩展名:
public static dynamic DaynamicMap(this Source source) { if (source.X == 1) return Mapper.Map(source); return Mapper.Map(source); } Console.WriteLine(new Source { X = 1, Y = 2 }.DaynamicMap()); Console.WriteLine(new Source { X = 2, Y = 2 }.DaynamicMap());