Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

automapper class to struct

Tags:

c#

automapper

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.

like image 610
cs0815 Avatar asked Oct 25 '25 02:10

cs0815


1 Answers

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);
like image 80
Sergey Berezovskiy Avatar answered Oct 26 '25 18:10

Sergey Berezovskiy