206mph
206mph

Reputation: 439

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?

Upvotes: 1

Views: 10233

Answers (2)

Lucian Bargaoanu
Lucian Bargaoanu

Reputation: 3516

If the default string format is good enough, this works by default in both directions, no type converters needed.

Upvotes: 6

fharreau
fharreau

Reputation: 2347

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.

Upvotes: 7

Related Questions