cs0815
cs0815

Reputation: 17388

automapper class to struct

Is it actually possible to map a class to a struct using AutoMapper?

At the moment I am getting:

{"The type initializer for 'AutoMapper.TypeMapFactory' threw an exception."}

This is my simplified code:

Mapper.CreateMap<A, B>()
.ForMember(dest => dest.a, opt => opt.MapFrom(src => src.b))
.ForMember(dest => dest.c, opt => opt.MapFrom(src => src.d))
.ForMember(dest => dest.f, opt => opt.MapFrom(src => src.g));

Here A is a class and B is a struct.

Upvotes: 4

Views: 3483

Answers (1)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236208

It is completely possible to map class instance to struct - AutoMapper do not have any constraints on generic type parameters, and it works fine with structs. E.g. if you have

public class A
{
    public string b { get; set; }
    public int d { get; set; }
    public bool g { get; set; }
}

public struct B
{
    public bool f;
    public string a;
    public int c;
}

With your mapping following code works just fine:

var a = new A { b = "b", d = 42, g = false };
var b = Mapper.Map<B>(a);

Upvotes: 5

Related Questions