AutoMapper with Generic Type Inheritance

I am trying to map a CustomerDTO to my ICustomer domain object with AutoMapper. Everything works fine for the first level of inheritance, but not for others.

I use interfaces for my domain model, since the concrete types are introduced by StructureMap from my LinqToSql infrastructure level.

public interface IBaseEntity<TPk>
{
    TPk Id { get; }
}

public interface ICustomer : IBaseEntity<int>
{
    string Email { get; set; }
}

[DataContract]
public class CustomerDTO
{
    [DataMember]
    public int Id { get; set; }

    [DataMember]
    public string Email { get; set; }
}

Now displaying AutoMapper

Mapper.CreateMap<CustomerDTO, ICustomer>();

Mapper.CreateMap<ICustomer, CustomerDTO>();

Mapper.AssertConfigurationIsValid();

Now when i use mapping

    public CreateCustomerServiceResult CreateCustomer(CustomerDTO customer)
    {
        var result = new CreateCustomerServiceResult();
        try
        {
            var originalMapped = Mapper.DynamicMap<CustomerDTO, ICustomer>(customer);

            var newCustomer = _customerService.CreateCustomer(originalMapped);

            var newMapped = Mapper.DynamicMap<ICustomer, CustomerDTO>(newCustomer);

            result.Customer = newMapped;
        }
        catch (Exception ex)
        {

        }
        return result;
    }

I have a dictionnary missing key exception in the "Id" property ...

+3
source share
1 answer

Got it!

The problem was due to the missing Id property setter for IBaseEntity.

After changing it, everything works

public interface IBaseEntity<TPk>
{
    TPk Id { get; set; }
}
+1
source

Source: https://habr.com/ru/post/1724355/


All Articles