
> OrderStatus.cs:
public enum OrderStatus { [Description("PaID")] PaID,[Description("Processing")] InProcess,[Description("Delivered")] Sent} > Order.cs:
public class Order { public int ID { get; set; } public List<Orderline> Orderlines { get; set; } public OrderStatus Status { get; set; }} > OrderDTO.cs:
public class OrderDTO { public int ID { get; set; } public List<OrderlineDTO> Orderlines { get; set; } public string Status { get; set; } } 在我的autoMapper.cs中使用以下配置:
cfg.CreateMap<Order,OrderDTO>().ForMember( dest => dest.Status,opt => opt.MapFrom(src => src.Status.ToString()));
投影工作,但我得到一个这样的OrderDTO对象:
- ID: 1 - Orderlines: List<Orderlines> - Sent //I want "Delivered"!
我不希望Status属性为“已发送”,我希望它作为其关联的Description属性,在本例中为“Delivered”.
我尝试了两种解决方案,但没有一种方法有效:
>使用Resolve使用autoMapper函数,如here所述,但是,如07100所述:
ResolveUsing is not supported for projections,see the wiki on liNQ projections for supported operations.
>使用静态方法通过Reflection返回String中的Description属性.
cfg.CreateMap<Order,opt => opt.MapFrom(src => EnumHelper<OrderStatus>.GetEnumDescription(src.Status.ToString())));
但这给了我以下错误:
liNQ to EntitIEs does not recognize the method ‘System.String
GetEnumDescription(System.String)’ method,and this method cannot be
translated into a store Expression.
然后,我该怎样才能做到这一点?
解决方法 您可以添加像这样的扩展方法(借用 this post中的逻辑):public static class ExtensionMethods{ static public string GetDescription(this OrderStatus This) { var type = typeof(OrderStatus); var memInfo = type.GetMember(This.ToString()); var attributes = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute),false); return ((DescriptionAttribute)attributes[0]).Description; }} 然后在地图中访问它:
cfg => { cfg.CreateMap<Order,OrderDTO>() .ForMember ( dest => dest.Status,opt => opt.MapFrom ( src => src.Status.GetDescription() ) );} 这导致您要求的:
Console.Writeline(dto.Status); //"Delivered",not "sent"
See a working example on DotNetFiddle
Edit1:不要认为你可以向liNQ实体添加像这样的本地查找功能.它只适用于liNQ对象.您应该追求的解决方案可能是数据库中的域表,允许您加入它并返回您想要的列,这样您就不必对autoMapper执行任何 *** 作.
总结以上是内存溢出为你收集整理的c# – 使用AutoMapper将字符串描述为字符串全部内容,希望文章能够帮你解决c# – 使用AutoMapper将字符串描述为字符串所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)