当字符串为空时,C#Automapper如何将字段设置为null [英] How C# Automapper can set the fields to null when the string is empty

查看:379
本文介绍了当字符串为空时,C#Automapper如何将字段设置为null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法设置我正在映射的类的所有属性,即string.Empty应该映射到NULL.

Is there a way to set all properties of a class, that I'm mapping, that is string.Empty should map to NULL.

 Mapper.CreateMap<TSource, TDest>();

我希望将字符串为空的TSource的所有属性都映射到TDest对应属性中的NULL.

I want that all Properties of TSource that are string Empty are mapped to NULL in TDest corresponding Properties.

我目前还没有找到一种方法来全局分配此条件,而无需为所有属性手动设置.

I've currently not found a way to globally assign this condition without setting it up for all Properties manually.

编辑

我仅需要用于特定映射,而不需要应用程序中定义的所有映射.

I need it only for a specific mapping not for all maps defined in my application.

推荐答案

cfg.CreateMap<string, string>().ConvertUsing(s=>s == "" ? (string)null : s);

这篇关于当字符串为空时,C#Automapper如何将字段设置为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆