简体   繁体   中英

Automapper String to Guid not working

I'd like to create a generic type converter that converts a Guid to a string and a string to a Guid depending on which direction I'm converting (DTO > VM or VM > DTO). Additionally, some properties have nullable Guids so I thought I could handle that too. I've tried the following with not luck:

CreateMap<string, Guid?>().ConvertUsing(value => !string.IsNullOrEmpty(value) ? Guid.Parse(value) : (Guid?)null);
CreateMap<string, Guid>().ConvertUsing(guid => Guid.Parse(guid));

and

CreateMap<Guid?, string>().ConvertUsing(guid => guid?.ToString("N"));
CreateMap<Guid, string>().ConvertUsing(guid => guid.ToString("N"));

Any suggestions on how I can get this to work?

This works on my computer:

Mapper.Initialize(cfg =>
{
    cfg.CreateMap<string, Guid>().ConvertUsing(s => Guid.Parse(s));
    cfg.CreateMap<string, Guid?>().ConvertUsing(s => String.IsNullOrWhiteSpace(s) ? (Guid?)null : Guid.Parse(s));
    cfg.CreateMap<Guid?, string>().ConvertUsing(g => g?.ToString("N"));
    cfg.CreateMap<Guid, string>().ConvertUsing(g => g.ToString("N"));
});

var guid = Guid.NewGuid();
var guidStr = Guid.NewGuid().ToString();

var guid1 = Mapper.Map<Guid>(guidStr);     // The guid is parsed successfully
var guid2 = Mapper.Map<Guid?>(null);       // Gets null as expected
var str1 = Mapper.Map<string>(guid);       // The guid is serialized successfully
var str2 = Mapper.Map<string>(null);       // Gets null as expected

Do you configure your Mapper like this, using the Initialize method?

It also works using the Mapper.Instance.Map methods instead of Mapper.Map directly.

如果默认字符串格式足够好,则默认情况下这在两个方向上都有效,不需要类型转换器。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM