简体   繁体   English

具有通用类型继承的AutoMapper

[英]AutoMapper With Generic Type Inheritance

I'm trying to map CustomerDTO with my domain entity ICustomer with AutoMapper. 我正在尝试使用AutoMapper将CustomerDTO映射到我的域实体ICustomer。 Everything works fine for first inheritance level but not for the others. 一切都适用于第一个继承级别,但不适用于其他级别。

I'm using Interfaces for my domain model since concrete types are injected by StructureMap from my LinqToSql Database Infrastructure layer. 我正在为我的域模型使用Interfaces,因为StructureMap从我的LinqToSql Database Infrastructure层注入具体类型。

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 the AutoMapper mapping 现在是AutoMapper映射

Mapper.CreateMap<CustomerDTO, ICustomer>();

Mapper.CreateMap<ICustomer, CustomerDTO>();

Mapper.AssertConfigurationIsValid();

Now where i'm using the 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've got a Dictionnary missing Key Exception on the "Id" property ... 我在“Id”属性上有一个Dictionnary缺少Key Exception ...

Got It! 得到它了!

The problem was due to the missing setter of "Id" property of IBaseEntity. 问题是由于缺少IBaseEntity的“Id”属性。

After changing it everything works 更改后一切正常

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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